Skip to content

Instantly share code, notes, and snippets.

@simonguo
Last active May 2, 2017 01:46
Show Gist options
  • Save simonguo/fec7a57e74facc58bc6fd85abd767006 to your computer and use it in GitHub Desktop.
Save simonguo/fec7a57e74facc58bc6fd85abd767006 to your computer and use it in GitHub Desktop.
A callback function for css file loaded
loadCssFile("style.css",()=>{
console.log('loaded');
});
//获取css里面设置的元素样式
function getStyle(node, name) {
if (!node) {
return;
}
if (node.currentStyle) { // IE/OP
return node.currentStyle[name];
} else { // FF/CM
return node.ownerDocument.defaultView.getComputedStyle(node, null)[name];
}
};
export default function loadCssFile(fileURL, callback) {
const container = document.getElementsByTagName('head')[0];
const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'screen';
link.href = fileURL;
container.appendChild(link);
//创建定时器,读取创建的div的样式是否是已经在css里面设置好的
const checktTimer = setInterval(function () {
const node = document.getElementById('css-hack-for-loaded');
//样式和css里面设置的一样,说明加载成功
if ('fixed' === getStyle(node, 'position')) {
clearInterval(checktTimer);
clearTimeout(timeoutTimer);
callback && callback();
}
}, 50);
// 创建超时定时器,防止css文件加载失败的情况
const timeoutTimer = setTimeout(function () {
clearInterval(checktTimer);
clearTimeout(timeoutTimer);
}, 10000);
}
#css-hack-for-loaded{
position:fixed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment