链接元素加载 [英] link element onload
问题描述
无论如何要监听 元素的 onload 事件?
Is there anyway to listen to the onload event for a <link>
element?
前例:
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'styles.css';
link.onload = link.onreadystatechange = function(e) {
console.log(e);
};
这适用于 元素,但不适用于
.还有其他方法吗?我只需要知道外部样式表中的样式何时应用于 DOM.
This works for <script>
elements, but not <link>
. Is there another way?
I just need to know when the styles in the external stylesheet has applied to the DOM.
更新:
注入一个隐藏的 ,将
添加到头部并监听
window.onload
事件在 iframe 中?它应该在加载 css 时触发,但它可能无法保证在顶部窗口中加载...
Would it be an idea to inject a hidden <iframe>
, add the <link>
to the head and listen for the window.onload
event in the iframe? It should trigger when the css is loaded, but it might not guarantee that it's loaded in the top window...
推荐答案
这有点像 hack,但是如果你可以编辑 CSS,你可以添加一个特殊的样式(没有可见的效果),你可以听使用这篇文章中的技术:http://www.west-wind.com/weblog/posts/478985.aspx
This is kind of a hack, but if you can edit the CSS, you could add a special style (with no visible effect) that you can listen for using the technique in this post: http://www.west-wind.com/weblog/posts/478985.aspx
您需要页面中的元素具有 CSS 会影响的类或 ID.当您的代码检测到其样式已更改时,CSS 已加载.
You would need an element in the page that has a class or an id that the CSS will affect. When your code detects that its style has changed, the CSS has been loaded.
正如我所说的 hack :)
A hack, as I said :)
这篇关于链接元素加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!