• JS动态引入js,CSS——动态创建script/link/style标签


    一.动态创建link方式

    我们可以使用link的方式.如下代码所示.

    function addCssByLink(url){  
        var doc=document;  
        var link=doc.createElement("link");  
        link.setAttribute("rel", "stylesheet");  
        link.setAttribute("type", "text/css");  
        link.setAttribute("href", url);  
      
        var heads = doc.getElementsByTagName("head");  
        if(heads.length)  
            heads[0].appendChild(link);  
        else  
            doc.documentElement.appendChild(link);  
    }  

    二.动态创建style方式

    但是,这样的话,需要加载整个css文件,但是那样有可能浪费一个http请求并占用一个服务器请求数,并等待上一段下载时间,所以,Firebug Lite采取的是将css代码写在js中,然后动态创建style标签的方法,正如下面所示

    function addCssByStyle(cssString){  
        var doc=document;  
        var style=doc.createElement("style");  
        style.setAttribute("type", "text/css");  
      
        if(style.styleSheet){// IE  
            style.styleSheet.cssText = cssString;  
        } else {// w3c  
            var cssText = doc.createTextNode(cssString);  
            style.appendChild(cssText);  
        }  
      
        var heads = doc.getElementsByTagName("head");  
        if(heads.length)  
            heads[0].appendChild(style);  
        else  
            doc.documentElement.appendChild(style);  
    }  

    这样的话,如果是较少的代码,可以比较方便的实现到动态加载css的效果,但是如果为了方便维护和管理,并没有等待时间限制,使用link方式更加合适

     

    三.动态创建script方式

    var script=document.createElement("script");  
    script.setAttribute("type", "text/javascript");  
    script.setAttribute("src", "JustWalking.js");  
    var heads = document.getElementsByTagName("head");  
    if(heads.length)  
        heads[0].appendChild(script);  
    else  
        document.documentElement.appendChild(script); 

    但是这种方式在IE内核的浏览器中支持,在google、360极速、firefox下却不行

    四.打印引入style方式

    document.write("<link rel="stylesheet" href="uild/style.css" type="text/css" media="screen"/>");  
    document.write("<script type="text/javascript" src="JustWalking.js"></script>");  
  • 相关阅读:
    条码解析的一片js
    再看.net本质(二)
    再看.net本质
    powerdesigner逆向导出oracle数据库结构显示备注
    powerdesigner逆向工程,从数据库导出PDM
    实现HTTP跳转到HTTPS
    opencart 模块开发详解
    Opencart 之 Registry 类详解
    OpenCart 之registry功用
    php+支付宝整合
  • 原文地址:https://www.cnblogs.com/wzzl/p/4885844.html
Copyright © 2020-2023  润新知