如何判断css加载完成?
要判断这个 CSS 文件是否加载完毕,各个浏览器的做法差异比较大。
IE下可以直接使用onload事件来监听css加载。
Firefox和webkit内核的浏览器,需要使用setTimeout来轮询判断
1、IE下判断的方法:
// 代码节选至seajs function styleOnload(node, callback) { // for IE6-9 and Opera if (node.attachEvent) { node.attachEvent('onload', callback); // NOTICE: // 1. "onload" will be fired in IE6-9 when the file is 404, but in // this situation, Opera does nothing, so fallback to timeout. // 2. "onerror" doesn't fire in any browsers! } }
2、Firefox和webkit内核浏览器可以通过node.sheet.cssRules属性是否存在来判断是否加载完毕。而且需要使用setTimeout间隔事件轮询(相关课程推荐:JS视频教程)
// 代码节选至seajs function poll(node, callback) { if (callback.isCalled) { return; } var isLoaded = false; if (/webkit/i.test(navigator.userAgent)) {//webkit if (node['sheet']) { isLoaded = true; } } // for Firefox else if (node['sheet']) { try { if (node['sheet'].cssRules) { isLoaded = true; } } catch (ex) { // NS_ERROR_DOM_SECURITY_ERR if (ex.code === 1000) { isLoaded = true; } } } if (isLoaded) { // give time to render. setTimeout(function() { callback(); }, 1); } else { setTimeout(function() { poll(node, callback); }, 1); } } setTimeout(function() { poll(node, callback); }, 0);
具体的实现方法,建议看看seajs的源码文件。
© 著作权归作者所有
举报
发表评论
0/200