异步 javascript 加载/执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4631845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:21:35  来源:igfitidea点击:

asynchronous javascript loading/executing

javascript

提问by Kai

In this post, asynchronous .js file loading syntax, someone said, "If the async attribute is present, then the script will be executed asynchronously, as soon as it is available."

在这篇关于异步 .js 文件加载语法的帖子中,有人说,“如果存在 async 属性,那么脚本将在可用时异步执行。”

(function() {
  var d=document,
  h=d.getElementsByTagName('head')[0],
  s=d.createElement('script');
  s.type='text/javascript';
  s.async=true;
  s.src='/js/myfile.js';
  h.appendChild(s);
}()); /* note ending parenthesis and curly brace */

My question is, what does "the script will be executed asynchronously" mean? Will this script be executed in a different thread from other javascripts in the page? If yes, should we worry about synchronization issue in the two threads?

我的问题是,“脚本将异步执行”是什么意思?该脚本是否会在与页面中其他 javascript 不同的线程中执行?如果是,我们是否应该担心两个线程中的同步问题?

Thanks.

谢谢。

采纳答案by selbie

It will not be executed on different thread. You do not have to worry about thread synchronization in this case.

它不会在不同的线程上执行。在这种情况下,您不必担心线程同步。

At some point later, after your current call stack unwinds, the download of myfile.js will complete. The browser and js framework will execute your script at some point after that.

稍后,在您当前的调用堆栈展开后,myfile.js 的下载将完成。浏览器和 js 框架将在之后的某个时间执行您的脚本。

回答by kijin

Usually, when you add an external script to an HTML document, the script will need to be downloaded and executed before anything else can be done on the page. In other words, the script blocks. This can take a lot of time if there are several scripts to download.

通常,当您向 HTML 文档添加外部脚本时,需要先下载并执行该脚本,然后才能在页面上执行任何其他操作。换句话说,脚本块。如果要下载多个脚本,这可能需要很长时间。

But when you load a script asynchronously, it doesn't block. The rest of the page can be loaded and other scripts can be executed while the async script is downloading. This makes pages load faster, but this also means that you can't be sure when the async script will be executed. So you can't just start using functions and objects from the async script. You have to wait and check for the async script to load.

但是当您异步加载脚本时,它不会阻塞。在下载异步脚本时,可以加载页面的其余部分并执行其他脚本。这使页面加载速度更快,但这也意味着您无法确定异步脚本何时执行。所以你不能从异步脚本开始使用函数和对象。您必须等待并检查异步脚本加载。

Example:

例子:

script1.js

脚本1.js

var foo = "bar";

script2.js

脚本2.js

alert(foo);

doc1.html

文档1.html

<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>

Result: "bar"

结果:“酒吧”

doc2.html

doc2.html

<script type="text/javascript" src="script1.js" async="true"></script>
<script type="text/javascript" src="script2.js"></script>

Result: "bar" or undefined, depending on whether or not script1.js has loaded yet.

结果:“bar”或未定义,取决于 script1.js 是否已加载。

No threads to worry about, though. One script executes after the other, but never both at the same time. It's just the order of execution that becomes unpredictable.

不过,无需担心线程。一个脚本在另一个脚本之后执行,但绝不会同时执行。只是执行顺序变得不可预测。

回答by goat

Downloadedasynchronously, not executedasynchronously. Also, it's not necessarily executed when the download finishes.

异步下载,不异步执行。此外,它不一定在下载完成时执行。

回答by Abed Yaseen

  (function(doc, script) {
    var js, 
        fjs = doc.getElementsByTagName(script)[0],
        add = function(url, id) {
            if (doc.getElementById(id)) {return;}
            js = doc.createElement(script);
            js.src = url;
            id && (js.id = id);
            fjs.parentNode.insertBefore(js, fjs);
        };

    // Google Analytics
    add(('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js', 'ga');
    // Google+ button
    add('https://apis.google.com/js/plusone.js');
    // Facebook SDK
    add('//connect.facebook.net/en_US/all.js', 'facebook-jssdk');
    // Twitter SDK
    add('//platform.twitter.com/widgets.js', 'twitter-wjs');
}(document, 'script'));

source: https://css-tricks.com/thinking-async/

来源:https: //css-tricks.com/thinking-async/