JavaScript, dynamically loading scripts and styles
A dynamic script
As the site needs become larger, so does the need for scripts. We have to introduce too many JS scripts to reduce the performance of the entire station, so there is the concept of dynamic scripting, the appropriate time to load the corresponding script.
For example: We want to detect the browser when we need to introduce detection files.
1 Dynamic load JS file
Window.onload =function() {//window.onload event, wait for HTML execution to complete, execute anonymous function //determine if the file to be loaded is loaded successfullyAlerttypeofbrowserdetect);};//Note: The judgment load is written on, outside the window.onload, that is, loading the code, otherwise the page will be generated after the <script> element tag is not connected//set a variable with a value of true to reload with a value of false without loading the filevarFlag =true;if(flag) {//executes the Load JS file function when the flag value is judged to be trueLoadscript (' Browserdetect.js ');}//define the Load JS function, receive a parameter to load the JS our path namefunctionloadscript (URL) {//Create <script> element tags varScript = document.createelement (' script '); //add an attribute to a labelScript.type = ' Text/javascript '; //add an attribute to a labelSCRIPT.SRC =URL; //add an attribute to a labelScript.charset = ' Utf-8 '; //get to the first document.getElementsByTagName (' head ') [0].appendchild (script);}
2 polymorphic Loading JS code
//Note: The judgment load is written on, outside the window.onload, that is, loading the code, otherwise the page will be generated after the <script> element tag is not connected//set a variable with a value of true to reload with a value of false without loading codevarFlag =true;if(flag) {//executes the Load JS code function when the flag value is judged to be trueLoadscript ();//Execute function}//define the Load JS code function,functionLoadscript () {//Create a script tag varScript = document.createelement (' script '); //add an attribute to a labelScript.type = ' Text/javascript '; //add an attribute to a labelScript.charset = ' Utf-8 '; //the code to executeScript.text = "alert (' Hello ')"; //add a script tag to the end of the child label of the first head tagdocument.getElementsByTagName (' head ') [0].appendchild (script);}
PS: Of course, if text is not supported, you can use different methods for different browser features. The wording is ignored here.
Two dynamic styles
To dynamically load style sheets, for example, to switch Web site skins. Style sheets are loaded in two ways: a <link> tag and a <style> tag.
1 Dynamically loading CSS files
Section 118th, JavaScript, dynamic load scripts and styles