Created
April 20, 2020 17:47
-
-
Save jhned/f6ef7fa3df712376a91bfa5e5615f706 to your computer and use it in GitHub Desktop.
Use setTimeout and querySelectorAll for IE11-compatible prefetch fallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function loadStylesheets() { | |
// Give it a few seconds so that the browsers that support prefetch + onload have a chance to load the styles. | |
// After a few seconds though, we should double-check to make sure the styles loaded. | |
setTimeout(function () { | |
var prefetchLinks = document.querySelectorAll('link[rel=prefetch]'); | |
// The onload attribute should be switching out the rel value from prefetch to stylesheet. | |
// If that hasn't happened, then we'll need to manually intervene. | |
if (0 === prefetchLinks.length) { | |
return false; | |
} | |
for (i = 0; i < prefetchLinks.length; i++) { | |
var prefetchLink = prefetchLinks[i]; | |
var linkType = prefetchLink.getAttribute('as'); | |
var linkOnload = prefetchLink.getAttribute('onload'); | |
if ('style' === linkType) { | |
// Update the link's rel attribute and clear out "as". | |
// This change should be reflected in the inspector in IE11 and Edge. | |
prefetchLink.setAttribute('rel', 'stylesheet'); | |
prefetchLink.removeAttribute('as'); | |
} | |
if ('' !== linkOnload) { | |
// Remove the onload attribute. | |
// This change should be reflected in the inspector in IE11 and Edge. | |
prefetchLink.removeAttribute('onload'); | |
} | |
} | |
}, 3000); | |
} | |
window.addEventListener('load', loadStylesheets, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment