Can I Load CSS Using the "load.js" Library?

javascript

Solution

Direct from the source code

   function asyncLoadScript(src) {
        return function (onload, onerror) {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = src;

My suggestion is to modify the script (which doesn't seem to contain much) to mirror the function but for a link tag, rather than a script tag.

to reflect OP's comment

The script is built on top of chain.js so it may be more complicated than expected.

Unless you want something else, I'm pretty sure what I wrote above is what you need to change, so it would look like:

   function asyncLoadScript(src) {
        return function (onload, onerror) {

// Get file extension
var ext = src.split('.').pop();
if (ext == "js")
{
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = src;
} else if (ext == "css")
{
                var script = document.createElement('link');
                script.type = 'text/css';
                script.href = src;
                script.rel = "stylesheet";
}

Theoretically that should work. Make another comment if it doesn't work.

Problem

I recently found out about load.js, but I can't seem to find any indication of whether or not this is possible... (Note: I can't find a 'load.js' tag..) I've got load.js successfully loading all my JS files, so I know it works. Has anyone got it working for loading CSS files as well? Update: remyabel's solution worked perfectly for loading the physical files, but it seems there are a few quirks to this process... For some reason, the order in which the CSS files are loaded and whether they're all done in one `load(file1,file2);` or in stages with `load(file1).then(file2);` seems to affect how the style rules are applied to the markup. I'm going to set up a few test cases on my local machine to try work out how or why this happens, but for now at least the files are being loaded. Final Note: Following on from the solution posted below, I've decided to use `head.appendChild(script);` instead of `head.insertBefore(script, head.firstChild);` to add the CSS elements to the DOM (still uses the original method for JS files). This doesn't affect the order in which files are fetched and processed, but it makes Load.js insert my CSS links in the same order they were listed and at the end of the header instead of the beginning.

Original source