JavaScript: how to avoid the problem with blocking stylesheets

We can avoid the problem with blocking stylesheets by loading them with JavaScript.

First of all, we need to define a JavaScript loader for our CSS files:


(function() {
    var Loader = function() {
        this.styles = [];
    };
    Loader.prototype = {
        registerStyle: function( style ) {
            this.styles.push( style );
        },
        enqueueStyle: function( handle ) {
            for( var i = 0; i < this.styles.length; i++ ) {
                if( this.styles[i].handle === handle ) {
                    this.writeStyle( this.styles[i] );
                }
            }
        },
        writeStyle: function( style ) {
            var head = document.querySelector( 'head' );
            var link = document.createElement( 'link' );
            link.setAttribute( 'rel', 'stylesheet' );
            link.setAttribute( 'type', 'text/css' );
            link.setAttribute( 'href', style.href );
            link.setAttribute( 'media', style.media );

            head.appendChild( link );
        }
    };

    window.Loader = Loader;
})();

Each element added to the stylesheets array is an object containing the path to our CSS file, the media attribute's value and a reference handle used to identify our stylesheet within the queue.

Now we can create an external stylesheet containing the following rule:


p {
    color: green;
}

Finally, we put all these things together in our HTML page:


<body>
        <script src="js/loader.js"></script>
        <script type="text/javascript">
        (function() {
            var loader = new Loader();
            loader.registerStyle({
                handle: 'test',
                media: 'screen',
                href: 'css/test.css'
            });
            loader.enqueueStyle( 'test' );
        })();   
        </script>
        
        <p>This should be green.</p>
        
</body>

Back to top