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]
js code:
照格式创建:<script src="../js/myJs.js" type="text/javascript"></script> [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] <ul id="ulList"> <li></li> <li></li> <li></li> </ul> 页面js www.2cto.com [html] <script src="../js/jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../js/cookies.jquery.js" type="text/javascript"></script> <script type="text/javascript"> var arrCss = [{ "color": "red" }, { "color": "yellow" }, { "color": "blue" } ] $(function () { //从cookie中读取有没有css的链接地址 var cssHrefCookie = $.cookie("cssName"); if (cssHrefCookie) { loadCss(cssHrefCookie); } $("#ulList > li").map(function (index, item) { $(item).css("background-color", arrCss[index].color).click(function () { //1.先移除页面中包括在arrCss数组中的颜色link $("link").map(function (index, item) { //页面中css链接的地址 var href = $(item).attr("href"); //遍历arrCss数组对其值与页面获得的值进行比对 $.map(arrCss, function (value, key) { //根据数组获得的css链接的地址 var cssHref = "css/" + arrCss[key].color + ".css"; if (cssHref == href) { //1.移除该link标签 $(item).remove(); } }); }); //动态加载css文件到页面中 var url = "css/" + arrCss[index].color + ".css"; loadCss(url); //保存当前用户的css地址到cookie中 $.cookie("cssName", url, { expires: 1 }); }); }); }); //动态加载css文件的函数 function loadCss(url) { //<link href="http://www.php1.cn/"> var link = document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = url; document.getElementsByTagName("head")[0].appendChild(link); } </script>