本文介绍了javascript:在LINK上捕获加载事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将事件处理程序附加到链接标记的load事件,以在样式表加载后执行某些代码。

i'm trying to attach an event handler to the load event of a link tag, to execute some code after a stylesheet has loaded.

new_element = document.createElement('link');
new_element.type = 'text/css';
new_element.rel = 'stylesheet';
new_element.href = 'http://domain.tld/file.css';
new_element.addEventListener('load', function() { alert('foo'); }, false);
document.getElementsByTagName('head')[0].appendChild(new_element)

i已经尝试过onreadystatechange

i have tried onreadystatechange as well

new_element.onreadystatechange = function() { alert('foo'); }

遗憾的是,这两种方法都没有触发警报..
此外,new_element.onload使用addEventListener注册'load'事件的处理程序后为null是正常的吗?

unfortunately neither approach results in an alert being triggered..Furthermore, new_element.onload is null after registering a handler for the 'load' event with addEventListener.. is that normal?

谢谢,
andrew

thanks,andrew

ps:我可能不会使用任何框架来解决这个问题

ps: i may not use any framework in solving this

推荐答案

对于CSS样式表(不是LINK元素)一般情况下)我使用手动间隔,通过戳它的规则长度。它适用于crossbrowser(AFAIT)。

For CSS stylesheets (not LINK elements in general) i'm using manual interval, by poking it's rules length. It works crossbrowser (AFAIT).

try {
  if ( cssStylesheet.sheet && cssStylesheet.sheet.cssRules.length > 0 )
    cssLoaded = 1;
  else if ( cssStylesheet.styleSheet && cssStylesheet.styleSheet.cssText.length > 0 )
    cssLoaded = 1;
  else if ( cssStylesheet.innerHTML && cssStylesheet.innerHTML.length > 0 )
    cssLoaded = 1;
}
catch(ex){}

在上面的代码中,cssStylesheet是DOMElement。

In code above, the cssStylesheet is DOMElement.

这篇关于javascript:在LINK上捕获加载事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:01
查看更多