The project needs to use dynamic loading CSS files, sorted out, and by the way the dynamic loading JS function written an object, first code:
var dynamicloading = {
css:function (path) {
if (!path | | | path.length = = 0) {
throw new Error (' argument ' path "I s 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);
}
object contains two completely independent methods, which are used to load CSS files and JS files, parameters are the file path to load. The principle is very simple: create different nodes for different load file types, then add the respective attributes, and finally throw them into the head tag. After testing, this method is compatible with each browser, safe, non-toxic, environmental protection, is the web developer work standing code.
Here is the calling code, which is exceptionally simple:
Dynamically loading CSS file
dynamicloading.css ("Test.css");
Dynamically loading JS file
dynamicloading.js ("Test.js");
The above is to tell you how to implement JavaScript dynamic loading CSS and JS files, I hope to help you learn.