样式加载判断

在前端中对于样式的加载判断情况,主要有以下几个难点:

  1. link标签的onload事件在不同浏览器中存在兼容性
  2. link标签对象的sheet 或者是 stylesheet 等对象只有高版本浏览器才会支持
  3. 样式文件也存在在跨域的情况
  4. 样式文件加载失败

其中对于link标签的onload事件,一般浏览器都是支持的,只是有的只支持将onload事件内嵌在HTML元素上。

就目前而言,我也只是解决了1,2两种情况,可以满足基本的使用,如果你有更好的办法,或者解决3,4的,请麻烦务必一定要告知与我!
谢谢~

function loadStyle(node, callback, timeout) {

	var isLoaded = false,
		timeout = timeout || 6e3,
		time = new Date().getTime(),
		curTime,

		function poll() {

			// 通过link对象的属性判断,但无法检测跨域的CSS文件,以及非HTTP环境。
			if (node['sheet'] || node['stylesheet']) {
				if (node['sheet'] && node['sheet']['cssRules'] || node['stylesheet'] && node['stylesheet']['rules']) {
					isLoaded = true;
				} else {
					curTime = new Date().getTime();
				}
			} else {
				curTime = new Date().getTime();
			}

			// 尝试是否可执行onload,对于Firefox可能不兼容
			node.addEventListener('load', function(e) {
				isLoaded = true;
			}, false);

			// 6s钟的超时时间
			if (curTime - time > timeout) {
				isLoaded = true;
			}

			if (isLoaded) {
				callback && callback();
			} else {
				setTimeout(arguments.callee, 100);
			}
		}

	if (node.attachEvent) { // IE 6 ~ 8 直接绑定onload事件
		node.attachEvent('onload', callback);
	} else {
		setTimeout(poll(node),0)
	}
}

调用:

var linkTag = document.getElementsByTagName('link')[0];
loadStyle(linkTag, function() {
	alert('success')
});
原文地址:https://www.cnblogs.com/HCJJ/p/6625653.html