Javascript异步加载,内部有jquery append()函数

Javascript async load with jquery append() function inside

本文关键字:append 函数 jquery 异步 加载 内部 Javascript      更新时间:2023-09-26

编辑:我正在寻找一种将javascript文件异步"包含"在另一个文件中的方法。

如果我加载这样的javascript文件:

<script src="http://my.website.com/file.js" async="" type="text/javascript"></script>

在javascript文件中,我有

$('head').append('<script src="http://other-website.com/other-file.js" type="text/javascript"></script>');

该文件是否仍将异步加载,包括other-file.js

我猜我需要像那样用异步来附加它

$('head').append('<script async="" src="http://other-website.com/other-file.js" type="text/javascript"></script>');

要完全加载所有javascript异步,对吗?

但在other-file.js中,我在file.js 中使用了一些函数

是的,您需要添加async属性,如果您依赖于其他文件,则需要一些复杂的逻辑来了解它何时加载。

有专门为这个目的而建的图书馆,你调查过吗?我可以推荐RequireJS,这样你就可以像这样包装你的代码:

require(["helper/util"], function(util) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until
    //util's dependencies have loaded, and the util argument will hold
    //the module value for "helper/util".
});

这取决于JS运行的位置(其中包含.append()行(,以及是否具有async属性。

如果它在文档的head中运行,并且它正在附加到head,那么如果附加的<script>标记没有async属性,它将不会异步(将阻塞(。

原因是file.js很可能在处理完文档的<head>之前加载并解析。JavaScript将阻止浏览器的HTTP连接,直到它解析完任何没有async的外部JS,这意味着它将在<head>中在其下方添加新的<script>标记,然后继续处理它并阻止HTTP连接,除非存在async属性。