Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @description checks if the userAgent is identified as a bot or crawler
- * @param {string} userAgent , navigator user-agent
- * @returns {boolean}
- */
- export const isCrawler = userAgent => {
- 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;
- return crawlerRegex.test(userAgent);
- };
- /**
- * @description checks if the stylesheets attributes contains styled-components specific attributes
- * @param attributes , represents a NamedNodeMap containing the list of attributes of an HTML style tag
- * @returns {boolean}
- */
- export const isStyledComponentStylesheet = attributes => {
- const conditions = ['data-styled', 'data-styled-version'];
- return Object.values(attributes).some(attribute =>
- conditions.some(c => attribute.nodeName === c),
- );
- };
- /**
- * Fetches styled-components stylesheets and concatenates them to create one Prerender-ready stylesheet.
- * Function based on Mozilla documentation : https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList
- */
- export const appendStyledComponents = () => {
- const css = [].slice
- .call(document.styleSheets)
- .reduce((prevSheet, styleSheet) => {
- if (styleSheet.cssRules) {
- if (isStyledComponentStylesheet(styleSheet.ownerNode.attributes))
- return (
- prevSheet +
- [].slice
- .call(styleSheet.cssRules)
- .reduce((prevRule, cssRule) => prevRule + cssRule.cssText, '')
- );
- }
- return prevSheet;
- }, '');
- const style = document.createElement('style');
- document.head.appendChild(style);
- style.type = 'text/css';
- style.appendChild(document.createTextNode(css));
- };
- /**
- * apply prerender changes in document head if needed
- */
- export const handlePrerender = () => {
- if (isCrawler(navigator.userAgent)) {
- appendStyledComponents();
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement