This article mainly introduces JavaScript dynamic loading of CSS and JS files. If you need it, refer to the need to use dynamic loading of CSS files in the project, by the way, the function of dynamically loading JS is integrated into an object, first the code is:
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? 1.1.9 "); // dynamically load the JS file dynamicLoading. js (" test. js? 1.1.9 ");
The above shows you how to dynamically load CSS and JS files using JavaScript. I hope it will be helpful for your learning.