Load CSS or JS Files Simply & Asynchronously

Scripts

Ever wonder about the simplest, fastest way to load a CSS file or a JavaScript file asynchronously? @ScottJehl from the Filament Group Inc. has been using and improving a couple of basic functions, which he calls loadCSS and loadJS, that do just that.

LoadCSS

Loading CSS asynchronously is tricky. Browsers tend to handle all CSS requests as if they’re essential, halting page rendering until the full CSS finishes loading and parsing. loadCSS is a function for loading CSS asynchronously.

Place the loadCSS function inline in the head of your page (it can also be included in an external JavaScript file if preferable).

LoadCSS

LoadJS

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

Place the loadJS function inline in the head of your page (it can also be included in an external JavaScript file if preferable). Then call it by passing it a JavaScript URL.

loadJS does nothing to manage execution order of requested scripts, so we do not advise using it to load multiple javascript files that depend on one another.

LoadJS

Share/Like