Skip to content

Instantly share code, notes, and snippets.

@soderalohastrom
Created June 12, 2014 23:10
Show Gist options
  • Save soderalohastrom/963081943195d279165b to your computer and use it in GitHub Desktop.
Save soderalohastrom/963081943195d279165b to your computer and use it in GitHub Desktop.
Load CSS via Script
<html>
<head>
<meta charset="utf-8">
<title>Load CSS via Script</title>
<script>
var ss = document.createElement( "link" );
var ref = document.getElementsByTagName( "script" )[ 0 ];
ss.rel = "stylesheet";
ss.href = "foo.css";
// temporary non-applicable media query to load it async
ss.media = "only foo";
ref.parentNode.insertBefore( ss, ref );
// set media back
setTimeout( function(){ ss.media = "all"; } );
</script>
</head>
<body>
<h1>Test page</h1>
<p>This page loads "foo.css" asynchronously with JavaScript from the <code>head</code> of the page.</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment