menu

Load CSS or JS Files Simply & Asynchronously

Posted by Scott on 07/14/2014

Ever wonder about the simplest, fastest way to load a CSS file or a JavaScript file asynchronously?

Well, we happen to think about these things a lot, and over the years we’ve been using and improving a couple of basic functions, which we call loadCSS and loadJS, that do just that. Here’s how they work, in brief.

Loading CSS asynchronously is tricky (NOTE: see our updated post on this here!). Browsers tend to handle all CSS requests as if they’re essential, halting page rendering until the full CSS finishes loading and parsing. But we frequently have cases where we know that a CSS file can be parsed after a page has rendered.

For these cases, there’s a workaround to ensure we don’t hold anything up: Many modern browsers will evaluate the media attribute of a stylesheet before requesting it; if the media doesn’t match the browser’s current conditions, they will deprioritize that stylesheet and load it in parallel while the page is rendered. Our loadCSS function takes advantage of this behavior to ensure a stylesheet is requested asynchronously, and after the request goes out, it gives the stylesheet media type of “all” that will ensure it still applies when it loads.

To use loadCSS, just call the loadCSS function and pass it a URL of a stylesheet to load.

Loading JavaScript asynchronously is a little more straight-forward than CSS, though it does come with its own “gotcha” or two to avoid.

A common issue comes from loader functions that insert scripts into the page using the appendChild method , as it can cause errors in old versions of IE when appending to elements that haven’t finished loading. Instead, it’s recommended to use the insertBefore method (Paul Irish’s post, Surefire DOM Insertion explains this situation and the rather than the insertBefore workaround well.) Also, if you’re loading multiple scripts with dependencies, you’ll need to manage their execution order. We typically recommend concatenating scripts into a single file and loading them via a single http request, so for our needs, a simple script is best.

Those concerns aside, loading a JavaScript file asynchronously is pretty simple: just inject a script tag into a reliable spot in the head of the page. We wrap a little function around that pattern that you can find at our loadJS project. Here’s how it works:

loadJS( "/path/to/my/script.js" );

Once again, you can find more info on loadJS at the project website: loadJS