本文介绍了onload handler和src的顺序在脚本元素中是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自此答案的:

el.onload = function() { //...
el.src = script;

您还应该在附加<$之前将脚本附加到DOM c $ c> onload 事件:

$body.append(el);
el.onload = function() { //...
el.src = script;

请记住,您需要检查 readystate IE支持。如果您使用的是jQuery,还可以尝试 getScript()方法:

Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: http://api.jquery.com/jQuery.getScript/

我对此持怀疑态度相信这将是问题的正确答案。

I am skeptical about believing that this would be the correct answer to the question.

那么,设置 onload 处理程序的顺序是什么 src 这么重要吗?我认为它们会被浏览器立即评估,所以我认为之间没有区别:

So, is the order of setting onload handler and src so important? I think they are evaluated by browser instantly so I think that there is no difference between:

el.onload = function() { //...
el.src = script;

el.src = script;
el.onload = function() { //...

我是对的吗?

推荐答案

@thinkbigthinksmall是对的。

@thinkbigthinksmall is right.

我想补充一点,这种行为是特定于webkit的,Firefox会对事件处理程序进行排队,因此在这种情况下无关紧要。

I would add that this behavior is webkit specific, Firefox will queue the event handler, so in this case it wouldn't matter.

我不确定规格是怎么说的,但IMM FF的行为是正确的。

I am not sure what the specs do say about it, but IMM FF behavior is the correct one.

无论如何,因为webkit的行为就像那样,在声明onload事件之后,应始终设置src,否则,缓存的媒体将在解析脚本之前触发onload事件。

Anyway, since webkit behaves like that, one should always set the src after the onload event has been declared, otherwise, cached media will fire the onload event before your script has been parsed.

一个解决方法是在声明onload事件后再次设置你的src:

One workaround though is to set your src again after the onload event has been declared :

<img src="someCachedMedia.ext" id="img"/>
<script>
  img.onload = doStuff;
  img.src = img.src; // force the onload to fire again
</script>

这样,您就可以确定onload事件将会触发。此外,应该进行单个请求,因为第一个请求将被缓存。

This way, you're sure the onload event will fire. Also, a single request should be made, since the first one will be cached.

这篇关于onload handler和src的顺序在脚本元素中是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:51