This article describes how to dynamically load scripts and styles in JavaScript. For more information, see
A dynamic script
When the demand for websites increases, the demand for scripts gradually increases. We have to introduce too many JS scripts to reduce the performance of the entire site;
Therefore, the concept of dynamic scripts is introduced, and corresponding scripts are loaded at the right time;
1. dynamically introduce js files
Var flag = true; if (flag) {loadScript ('browserdetect. js '); // call the function and introduce the path;} function loadScript (url) {var script = document. createElement ('script'); // create a script tag; script. type = 'text/javascript '; // set the type attribute; script. src = url; // introduce url; document. getElementsByTagName ('head') [0]. appendChild (script); // introduce the scriptMedium ;}
2. dynamically execute js Code
Var script = document. createElement ('script'); script. type = 'text/javascript '; var text = document. createTextNode ("alert ('lil')"); // sets the script TAG content; IE reports an error; script. appendChild (text); document. getElementsByTagName ('head') [0]. appendChild (script); // PS: the IE browser considers the script as a special element and cannot access subnodes. // for compatibility, the text attribute can be used instead. function loadScriptString (code) {var script = document. createElement ("script"); script. type = "text/javascript"; try {// The IE browser considers the script as a special element and cannot access subnodes. An error is returned. script. appendChild (document. createTextNode (code); // W3C method;} catch (ex) {script. text = code; // IE Method;} document. body. appendChild (script) ;}// call; loadScriptString ("function sayHi () {alert ('Hi ')}");
2. Dynamic Style
To dynamically load style sheets, such as switching the website skin;
There are two ways to load styles, one is Tag, one is