Advertisement
Guest User

Untitled

a guest
Apr 10th, 2020
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @description checks if the userAgent is identified as a bot or crawler
  3.  * @param {string} userAgent , navigator user-agent
  4.  * @returns {boolean}
  5.  */
  6. export const isCrawler = userAgent => {
  7.   const crawlerRegex = /googlebot|adsbot-google|headless|prerender|Feedfetcher-Google|bingbot|yandex|baiduspider|Facebot|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|bufferbot|redditbot|Applebot|WhatsApp|flipboard|tumblr|bitlybot|Discordbot|qwantify|www.google.com\/webmasters\/tools\/richsnippets|cocon/i;
  8.   return crawlerRegex.test(userAgent);
  9. };
  10.  
  11. /**
  12.  * @description checks if the stylesheets attributes contains styled-components specific attributes
  13.  * @param attributes , represents a NamedNodeMap containing the list of attributes of an HTML style tag
  14.  * @returns {boolean}
  15.  */
  16. export const isStyledComponentStylesheet = attributes => {
  17.   const conditions = ['data-styled', 'data-styled-version'];
  18.   return Object.values(attributes).some(attribute =>
  19.     conditions.some(c => attribute.nodeName === c),
  20.   );
  21. };
  22.  
  23. /**
  24.  * Fetches styled-components stylesheets and concatenates them to create one Prerender-ready stylesheet.
  25.  * Function based on Mozilla documentation : https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList
  26.  */
  27. export const appendStyledComponents = () => {
  28.   const css = [].slice
  29.     .call(document.styleSheets)
  30.     .reduce((prevSheet, styleSheet) => {
  31.       if (styleSheet.cssRules) {
  32.         if (isStyledComponentStylesheet(styleSheet.ownerNode.attributes))
  33.           return (
  34.             prevSheet +
  35.             [].slice
  36.               .call(styleSheet.cssRules)
  37.               .reduce((prevRule, cssRule) => prevRule + cssRule.cssText, '')
  38.           );
  39.       }
  40.       return prevSheet;
  41.     }, '');
  42.  
  43.   const style = document.createElement('style');
  44.   document.head.appendChild(style);
  45.   style.type = 'text/css';
  46.   style.appendChild(document.createTextNode(css));
  47. };
  48.  
  49. /**
  50.  * apply prerender changes in document head if needed
  51.  */
  52. export const handlePrerender = () => {
  53.   if (isCrawler(navigator.userAgent)) {
  54.     appendStyledComponents();
  55.   }
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement