如何判断css是否加载完成?

在通过ajax或者src动态获取js、css文件的时候,我们常常需要判断文件是否加载完成,以便进行进一步的操作。那么如何判断css是否加载完成?下面本篇文章就来给大家介绍一下,希望对大家有所帮助。

判断CSS是否加载完成的方法:

在head标签内插入 引入css的link标签,如果是ie浏览器直接使用onload事件,其它浏览器用setTimeout循环轮询判断下面属性:

  • 如果是webkit内核判断 link节点上的sheet属性

  • 其它浏览器判断节点上的sheet.cssRules属性

function loadCss(src, fn) {
    var node = document.createElement('link');
    node.rel = 'stylesheet';
    node.href = src;
    
    document.head.insertBefore(node, document.head.firstChild);
    
    if (node.attachEvent) {//IE
        node.attachEvent('onload', function () {
            fn(null, node)
        });
    } else {//other browser
        setTimeout(function () {
            poll(node, fn);
        }, 0);
    }
    function poll(node, callback) {
        var isLoaded = false;
        if (/webkit/i.test(navigator.userAgent)) {//webkit
            if (node['sheet']) {
                isLoaded = true;
            }
        } else if (node['sheet']) {// for Firefox
            try {
                if (node['sheet'].cssRules) {
                    isLoaded = true;
                }
            } catch (ex) {
                // NS_ERROR_DOM_SECURITY_ERR
                if (ex.code === 1000) {
                    isLoaded = true;
                }
            }
        }
        if (isLoaded) {
            setTimeout(function () {
                callback(null, node);
            }, 1);
        } else {
            setTimeout(function () {
                poll(node, callback);
            }, 10);
        }
    }

    node.onLoad = function () {
        fn(null, node);
    }
}

补:js文件加载

function loadScript(src, fn) {
    var node = document.createElement("script");
    node.setAttribute('async', 'async');
    var timeID;
    var supportLoad = "onload" in node ;
    var loadEvent = supportLoad ? "onload" : "onreadystatechange";
    node[loadEvent] = function onLoad() {
        if (!supportLoad && !timeID && /complete|loaded/.test(node.readyState)) {
            timeID = setTimeout(onLoad);
            return;
        }
        if (supportLoad || timeID) {
            clearTimeout(timeID);
            fn(null, node);
        }
    };
    document.head.insertBefore(node, document.head.firstChild);
    node.src = src;
    node.onerror = function (e) {
        fn(e);
    };
}

更多前端开发知识,请查阅 HTML中文网 !!

以上就是如何判断css是否加载完成?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑