How to achieve JavaScript dynamic loading of CSS and JS files, javascriptcss
The project needs to use the dynamic loading of CSS files. After sorting it out, the function of dynamic loading of JS is integrated into an object, first go to the Code:
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. The parameters are the file paths to be loaded. The principle is very simple: create different nodes for different loading file types, add their respective attributes, and finally put them in the head tag. Tested, this method is compatible with various browsers and is secure, non-toxic, and environmentally friendly. It is a constant code for web developers.
The following is the call code. The exception is simple:
// Dynamically load the CSS file dynamicloading.css ("test.css"); // dynamically load the JS file dynamicLoading. js ("test. js ");
The above shows you how to dynamically load CSS and JS files using JavaScript. I hope it will be helpful for your learning.