通过与异步属性HTML5脚本标签的Javascript执行顺序

通过与异步属性HTML5脚本标签的Javascript执行顺序

本文介绍了通过与异步属性HTML5脚本标签的Javascript执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阿罗哈。我一直在努力的脚本,虽然我理解这个问题的各个组成部分的文件(并看着许多其他问题上的SO),我不明白,这在实践中的具体行为。请注意,以下code是一个简短的子集隔离的具体问题。这里是 async.html

Aloha. I have been working on a script and though I understand documentation of each constituent of the problem (and have looked over many other questions on SO), I don't understand this specific behavior in practice. Please be aware that the following code is an abbreviated subset that isolates the specific issue. Here is async.html:

<!doctype html>
<html><head><script type="text/javascript" src="asyncTest.js" async="true"></script></head>
<body><ul id="menu"><li>one</li><li>two</li><li>three</li></ul></body></html>

这是 asyncTest.js

var _site = function() {
  var load = function() {
    var menuCategory = document.getElementById('menu').getElementsByTagName('li');
    for(var i=0; i<menuCategory.length; i++) { alert(i+'['+menuCategory[i]+']'); }
  };

  return { load:load };
}();
window.addEventListener('load',_site.load(),false);

问题是,没有在&LT的异步属性;脚本&GT; 标签,这code不正确地储存&LT;李&GT; 元素融入到 menuCategory ,就好像它是先于DOM被加载运行(虽然我认为它应该在整个窗口对象,加载后火)。我觉得奇怪,因为我使用的的addEventListener()来尝试和运行这个整个事情已经加载之后才(和它似乎在铬适当的时间运行,FF和Opera - 至少这似乎是适当的时间)。如果有的话,我认为会相反导致此行为。

The problem is that without the async attribute in the <script> tag, this code does not properly store the <li> elements into menuCategory, as though it were running prior to the DOM being loaded (even though I thought it should fire after the entire window "object" loads). I find that strange because I am using the addEventListener() to try and run this only after the whole thing has been loaded (and it appears to run at the appropriate time in Chromium, FF, and Opera -- at least what appears to be the "appropriate time"). If anything, I think that the opposite would cause this behavior.

有人可以解释这一点,pferably使用旧爱因斯坦$ P $解释它就像你它解释的是六十岁?我显然缺少我的阅读的东西。谢谢!

Can someone explain this, preferably using the old Einstein "explain it like you're explaining it to a six-year-old"? I'm obviously missing something in my reading. Thanks!

推荐答案

由于在评论中提到RobG,这里的问题是,使用 _site.load()(与呼叫后括号),导致被执行的功能,然后分配到的onload 事件。要纠正此行为所需的功能的方法是调用它没有括号: _site.load (或 _site()负载)。

As mentioned by RobG in the comments, the problem here is that using _site.load() (with parenthesis after the call) is causing the function to be executed AND THEN assigned to the onload event. The way to correct this behavior to the desired functionality is to call it without the parenthesis: _site.load (or _site().load).

这篇关于通过与异步属性HTML5脚本标签的Javascript执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:13