Project needs to use the dynamic loading of CSS files, organized a bit, by the way, the combination of dynamic loading JS function as an object, first on the code:
?
1234567891011121314151617181920212223 |
var dynamicLoading = {
css:
function
(path){
if
(!path || path.length === 0){
throw new Error(
‘argument "path" is required !‘
);
}
var head = document.getElementsByTagName(
‘head‘
)[0];
var link = document.createElement(
‘link‘
);
link.href = path;
link.rel =
‘stylesheet‘
;
link.type =
‘text/css‘
;
head.appendChild(link);
},
js:
function
(path){
if
(!path || path.length === 0){
throw new Error(
‘argument "path" is required !‘
);
}
var head = document.getElementsByTagName(
‘head‘
)[0];
var script = document.createElement(
‘script‘
);
script.src = path;
script.type =
‘text/javascript‘
;
head.appendChild(script);
}
}
|
The object contains two completely independent methods for loading CSS files and JS files, and the parameters are the file paths to be loaded. The principle is simple: create different nodes for different load file types, then add their own properties, and finally throw them into the head tag. Tested, this method is compatible with each browser, safe, non-toxic, environmental protection, is the web developer work standing code.
Here is the calling code, the exception is simple:
?
12345 |
//动态加载 CSS 文件 dynamicLoading.css( "test.css" ); //动态加载 JS 文件 dynamicLoading.js( "test.js" ); |
Javascript_ dynamically loading CSS and JS files