0

I have two different javascripts. I would like to start a function only after both of those js files or scripts have loaded, because they need to access each other's functions and/or variables.

I don't know which one will load first.

What is the proper way of doing it?

NOTE: one of the scripts (A) loads data asynchronously and the script (B) needs to wait till all the data is loaded and started before it can continue (ex youtube video is loaded from (A) and needs to start playing before (B) can execute)

4

2 回答 2

2

<script>一般都是同步加载的。文档的评估停止等待,直到脚本被加载并执行。它是这样处理的,因为脚本可能会通过使用类似的东西来干扰文档document.write(),因此解析器不能确定文档的其余部分是否保持当时的显示方式。

因此,要在加载脚本后执行您的脚本,只需在<script>加载脚本的那两个后面放置一个包含启动代码的第三个标签。

<script src="scriptA.js"></script>
<script src="scriptB.js"></script>
<script>
  // start something of scriptB
  scriptB.start();
</script>
于 2012-11-20T10:33:11.040 回答
0

由于脚本是同步加载的,只需在这两个文件之后加载执行其功能的脚本即可。无论如何,如果您有依赖项的脚本,我会鼓励您使用模块加载器,例如RequireJS。这样,您可以定义在执行开始之前应该加载哪些模块/文件。

于 2012-11-20T10:39:14.573 回答