EN
JavaScript - insert *.css file element keeping correct imports order
8 points
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:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<!--
5
WARNING: it is necessary to keep correct initial order for imported style files.
6
7
it means position priority
8
|
9
v -->
10
<link rel="stylesheet" type="text/css" href="/style.1.css" />
11
<link rel="stylesheet" type="text/css" href="/style.2.css" />
12
<link rel="stylesheet" type="text/css" href="/style.5.css" />
13
<link rel="stylesheet" type="text/css" href="/style.6.css" />
14
</head>
15
<body>
16
<script>
17
18
// Reusable logic:
19
20
var container = document.head;
21
22
var findStyles = function() {
23
return container.querySelectorAll('link[rel="stylesheet"]');
24
};
25
26
var createStyle = function(url) {
27
var element = document.createElement('link');
28
element.rel = 'stylesheet';
29
element.type = 'text/css';
30
element.href = url;
31
return element;
32
};
33
34
var insertStyle = function(url, comparePaths) {
35
var styles = findStyles();
36
if (styles.length > 0) {
37
var error = -Infinity;
38
var placeholder = null;
39
for (var i = 0; i < styles.length; ++i) {
40
var item = styles[i];
41
if (item.href) {
42
var result = comparePaths(url, item.href);
43
if (result === 0) {
44
return;
45
}
46
if (result < 0 && result > error) {
47
error = result;
48
placeholder = item;
49
}
50
}
51
}
52
if (placeholder != null) { // null or undefined
53
var style = createStyle(url);
54
container.insertBefore(style, placeholder);
55
return;
56
}
57
}
58
var style = createStyle(url);
59
container.appendChild(style);
60
};
61
62
63
// Usage example:
64
65
var pattern = /\.(\d+)\.css$/i;
66
67
var findPriority = function(path) { // finds path priority that matches `pattern` expression
68
var match = pattern.exec(path);
69
if (match) {
70
return parseInt(match[1]);
71
}
72
return null;
73
};
74
75
var comparePaths = function(a, b) { // compares paths that match `pattern` expression
76
var aPriority = findPriority(a);
77
var bPriority = findPriority(b);
78
return aPriority - bPriority;
79
};
80
81
insertStyle('/style.7.css', comparePaths); // inserts '/style.7.css' style to web page
82
insertStyle('/style.4.css', comparePaths); // inserts '/style.4.css' style to web page
83
insertStyle('/style.4.css', comparePaths); // dupplicated insert should be ommited
84
insertStyle('/style.3.css', comparePaths); // inserts '/style.3.css' style to web page
85
86
87
// Logic verification:
88
89
var elements = findStyles();
90
for (var i = 0; i < elements.length; ++i) {
91
console.log(elements[i].outerHTML);
92
}
93
94
</script>
95
</body>
96
</html>