Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Defer loading of non-critical CSS using XHR
<html>
<head>
<style>
.blue{color:blue;}
</style>
</head>
<body>
<div class="blue">
Hello, world!
</div>
<script type="text/javascript" async>
function loadXMLDoc() {
var xmlhttp, css,
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
css=xmlhttp.responseText;
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}
}
xmlhttp.open("GET","css/mycssfile.css",true);
xmlhttp.send();
}
window.onload = loadXMLDoc;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.