Introduction:
Recently, I often encounter some people asking about the need for on-demand loading in web pages. For example, js files are not loaded when the web page is loaded. Only when the user triggers an event, the js files required are loaded as needed. , and for example, users can switch the color of web pages at will. Looking at these requirements analysis, it is nothing more than a dynamic loading in js, so it is necessary to make several demos for your reference.
1. Execute a function after dynamically loading the js file in the web page:
Elements in the web page:
[html]
4562f0883688e03d29c994dd4b9861dc
js code:
照格式创建: [html] document.getElementById("btn1").onclick = function () { var url = "js/myjs.js"; if (!checkIsExist(url)) { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "../" + url; document.body.appendChild(script); } setTimeout("sayHi()", 100); //加载完成后,执行其内部的函数 } //检查页面中是否存在重名的js文件 function checkIsExist(url) { var scripts = document.getElementsByTagName("script"); //遍历查询页面中已存在有想要加载的js文件 for (var i = 0; i < scripts.length; i++) { if (scripts[i].src.indexOf(url)>-1) { return true; } } return false; }
js file is dynamically loaded and run!
2. Dynamically load css files to implement skin change
Page style
[html]
#ulList li{ list-style-type: none; height:50px; width:50px; background-color: Green; margin-right:5px; float:left;}
The three css files are: red.cssyellow.cssblue.css, which are saved in the css folder. Their content is background-color: corresponding to the color of the file name.
Page layout
[html]