动态加载脚本和样式

动态加载脚本文件

视窗移动到需要加载脚本的地方,将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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值