JavaScript learning 10: dynamically loading scripts and styles
When writing web pages, we need to introduce a lot of JavaScript script files and CSS style files. Especially when there is a large demand for websites, the demand for scripts also increases. As a result, the performance of the website will be greatly reduced, so the concept of dynamic loading emerged, that is, loading the corresponding script and style as needed. Next, let's take a look at how to implement dynamic loading.Dynamic script:Let's take a look at a sample code for dynamically loading js files:
// Dynamically load JSvar flag = false; if (flag) {loadScript ('browserdetect. js ');} function loadScript (url) {var script = document. createElement ('script'); script. type = 'text/javascript '; script. src = url; document. getElementsByTagName ('head') [0]. appendChild (script );}In this way, we only need to control the flag value to determine whether the js script file is loaded to the current page. Let's take a look at an example of dynamic JavaScript Execution:
// Dynamically execute JSvar flag = true; if (flag) {executeScript ();} function executeScript () {var script = document. createElement ('script'); script. type = 'text/javascript '; var text = document. createTextNode ("alert ('liany')"); script. appendChild (text); document. getElementsByTagName ('head') [0]. appendChild (script );}
Dynamic StyleWe are certainly familiar with all kinds of skin-changing functions, but you have never thought about how skin-changing works. I also learned this and suddenly realized that it turned out that the advanced skin-changing feature was so simple: just change the CSS style. Let's take a look at how the webpage style is dynamically loaded. A style sheet can be loaded in either of the following ways: Tag, one is