One dynamic script
As the demand for the website increases, the demand for scripts also gradually increases; we have to introduce too many JS scripts and reduce the performance of the entire site;
So the concept of dynamic scripts emerged, loading the corresponding scripts at the right time;
1. Dynamically introduce js files
var flag = true; if(flag){ loadScript('browserdetect.js'); // 调用函数,引入路径; } function loadScript(url){ var script = document.createElement('script'); // 创建script标签; script.type = 'text/javascript'; // 设置type属性; script.src = url; // 引入url; document.getElementsByTagName('head')[0].appendChild(script); // 将script引入<head>中; }
2. Dynamically execute js code
var script = document.createElement('script'); script.type = 'text/javascript'; var text = document.createTextNode("alert('Lee')"); // 设置script标签内容;IE会报错; script.appendChild(text); document.getElementsByTagName('head')[0].appendChild(script); // PS:IE浏览器认为script是特殊元素,不能再访问子节点; // 为了兼容,可以使用text属性来代替; function loadScriptString(code){ var script = document.createElement("script"); script.type = "text/javascript"; try{ // IE浏览器认为script是特殊元素,不能再访问子节点;报错; script.appendChild(document.createTextNode(code)); // W3C方式; }catch(ex){ script.text = code; // IE方式; } document.body.appendChild(script); } // 调用; loadScriptString("function sayHi(){alert('hi')}");
2 Dynamic Style
In order to dynamically load style sheets, such as switching website skins;
There are two ways to load styles, one is the tag, the other is the