在网页中动态加载 CSS 样式文件

JavaScript   2006-11-22 15:57   阅读1567   评论3  
字号:    
无聊, 写了个动态加载 CSS 文件的脚本。至于有什么用处, 以后再说。


/**
 * dynamic-style.js
 * 作者: 我
 * 时间: 2006 年 11 月 26 日
 */
( function() {
var drv = {}; window.Driver = drv;

if(document.all) { // For IE
    drv.XMLHttpRequest = function() {
        var xmlhttp = null;
        /*@cc_on @*/
        /*@if (@_jscript_version >= 5)
        try    { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e) {
            try    { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (E) { xmlhttp = false; } }
            @end @*/
        return xmlhttp;
    };

    window.DynamicStyle = function(s) {
        var uid = __push__(s);
        document.createStyleSheet('"' + uid + '");');
    };

    window.__tmp__ = {};
    window.__push__ = function(s) {
        var uid = "_" + Math.ceil(Math.random() * 16777216) + "_" + (new Date()).getTime();
        window.__tmp__[uid] = s;
        return uid;
    };
    window.__pop__ = function(uid) {
        var s = window.__tmp__[uid];
        window.__tmp__[uid] = undefined;
        return s
    };

} else { // For Gecko
    drv.XMLHttpRequest = function() {
        return xmlhttp = new XMLHttpRequest();
    };

    window.DynamicStyle = function(s) {
        var d = document.createElement('STYLE'); d.type = 'text/css';
        document.body.appendChild(d);
        d.innerHTML = s;
    };
} // Driver End

window.LazyLoadStyle = function(url) {
    var xh = Driver.XMLHttpRequest();
    xh.onreadystatechange = function() {
        if(xh.readyState == 4) {
            if(xh.status == 200) {
                DynamicStyle(xh.responseText);
            } else {
                alert('糟糕, 下载失败!');
            }
        }
    };
    xh.open('GET', url, true); xh.send(null);
};

} )();



参考资料: 动态创建 Style 节点 (mmommo's blog)

评论(?)
阅读(?)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
网易公司版权所有 ©1997-2009