Languages
[Edit]
EN

JavaScript - insert *.css file element keeping correct imports order

8 points
Created by:
Palpys
764

In this article, we would like to show how in JavaScript, add <link> element in the proper position that imports *.css file to the web page.

That solution lets to import *.css files keeping styles in order. To detect order it is necessary to provide a function that compares which path should be before another one.

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <!--
  WARNING: it is necessary to keep correct initial order for imported style files.

                                         it means position priority
                                                      |
                                                      v     -->
  <link rel="stylesheet" type="text/css" href="/style.1.css" />
  <link rel="stylesheet" type="text/css" href="/style.2.css" />
  <link rel="stylesheet" type="text/css" href="/style.5.css" />
  <link rel="stylesheet" type="text/css" href="/style.6.css" />
</head>
<body>
  <script>
    
    // Reusable logic:

    var container = document.head;
    
    var findStyles = function() {
        return container.querySelectorAll('link[rel="stylesheet"]');
    };
    
    var createStyle = function(url) {
        var element = document.createElement('link');
        element.rel = 'stylesheet';
        element.type = 'text/css';
        element.href = url;
        return element;
    };
    
    var insertStyle = function(url, comparePaths) {
        var styles = findStyles();
        if (styles.length > 0) {
            var error = -Infinity;
            var placeholder = null;
            for (var i = 0; i < styles.length; ++i) {
                var item = styles[i];
                if (item.href) {
                    var result = comparePaths(url, item.href);
                    if (result === 0) {
                        return;
                    }
                    if (result < 0 && result > error) {
                        error = result;
                        placeholder = item;
                    }
                }
            }
            if (placeholder != null) { // null or undefined
                var style = createStyle(url);
                container.insertBefore(style, placeholder);
                return;
            }
        }
        var style = createStyle(url);
        container.appendChild(style);
    };
    
    
    // Usage example:
    
    var pattern = /\.(\d+)\.css$/i;

    var findPriority = function(path) { // finds path priority that matches `pattern` expression
        var match = pattern.exec(path);
        if (match) {
            return parseInt(match[1]);
        }
        return null;
    };
    
    var comparePaths = function(a, b) { // compares paths that match `pattern` expression
        var aPriority = findPriority(a);
        var bPriority = findPriority(b);
        return aPriority - bPriority;
    };

    insertStyle('/style.7.css', comparePaths);  // inserts '/style.7.css' style to web page
    insertStyle('/style.4.css', comparePaths);  // inserts '/style.4.css' style to web page
    insertStyle('/style.4.css', comparePaths);  // dupplicated insert should be ommited
    insertStyle('/style.3.css', comparePaths);  // inserts '/style.3.css' style to web page


    // Logic verification:
    
    var elements = findStyles();
    for (var i = 0; i < elements.length; ++i) {
        console.log(elements[i].outerHTML);
    }
    
  </script>
</body>
</html>

 

Alternative titles

  1. JavaScript - import *.css file link element in proper position (keeping correct imports order)
  2. JavaScript - include *.css file link element in proper position (keeping correct imports order)
  3. JavaScript - attach *.css file link element in proper position (keeping correct imports order)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join