动态加载脚本文件
视窗移动到需要加载脚本的地方,将test改变为true来加载脚本
var test=true;
window.onload=function(){
if(test){
var script=document.createElement("script");
script.src="index1.js";
var head=document.getElementsByTagName("head")[0];
head.appendChild(script);
console.log(head);
}
}
动态加载js语句
var test=true;
window.onload=function(){
if(test){
var script=document.createElement("script");
script.text="aa()"; //使用的是script的Text属性,如果使用text
var head=document.getElementsByTagName("head")[0];
head.appendChild(script);
console.log(head);
}
}
function aa(){
console.log(121)
}
动态加载样式表
var test=true;
window.onload=function(){
if(test){
var link=document.createElement("link");
link.rel="stylesheet";
link.href="test.css";
var head=document.getElementsByTagName("head")[0];
head.appendChild(link);
}
}
动态执行style
var test=true;
window.onload=function(){
if(test){
var style=document.createElement("style");
style.type="text/css";
var head=document.getElementsByTagName("head")[0];
head.appendChild(style);
insertRule(document.styleSheets[0],"#box","background:red")
}
}
function insertRule(sheet,selectorText,cssText,position){
if(sheet.insertRule){
sheet.insertRule(selectorText+"{"+cssText+"}",position); //非IE
}
else if(sheet.addRule){
sheet.addRule(selectorText,cssText,position) //IE
}
}