Skip to content

Instantly share code, notes, and snippets.

@thienedits
Last active August 29, 2015 14:08
Show Gist options
  • Save thienedits/d99aa3f841a1a156d47a to your computer and use it in GitHub Desktop.
Save thienedits/d99aa3f841a1a156d47a to your computer and use it in GitHub Desktop.
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