我正在尝试将事件处理程序附加到链接标记的加载事件,以便在加载样式表后执行一些代码。
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)
我也试过onreadystatechange
:
new_element.onreadystatechange = function() { alert('foo'); }
不幸的是,这两种方法都不会触发警报。
此外,在使用 addEventListener
为 load
事件注册处理程序后,new_element.onload
为空。这正常吗?
PS:我可能不会使用任何框架来解决这个问题。
最佳答案
在我看来,这是使用 IMG 标记及其 onerror 事件解决此问题的更好解决方案。此方法无需循环、遵循扭曲的样式或在 iframe 中加载文件等即可完成工作。此解决方案在加载文件时正确触发,如果文件已被缓存则立即触发(具有讽刺意味的是,这比大多数 DOM 的方式要好加载事件处理缓存的 Assets )。这是我博客上的一篇文章,解释了该方法 - Back Alley Coder post - 我只是厌倦了没有合法的解决方案,享受吧!
var loadCSS = function(url, callback){
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
var img = document.createElement('img');
img.onerror = function(){
if(callback) callback(link);
}
img.src = url;
}
关于javascript - 捕获 LINK 上的加载事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2635814/