运行 关于异步延迟问题的多个脚本
Running multiple scripts on async defer problems
我有 2 个脚本,它们应该 运行 带有异步延迟。但问题是第二个脚本依赖于第一个脚本。 js-map-label.js
需要 运行 只有在 googleapis
已经加载并且 运行ning 之后。使用此设置,它在 80% 的时间内都有效。但有时它不会 运行,所以我不得不一遍又一遍地刷新,直到 js-map-label.js
运行。有什么办法可以解决这个问题吗?
我有这些脚本的顺序:
...
<script src="https://maps.googleapis.com/maps/api/js?key=__MY_KEY_HERE__...." async defer></script>
<script src="/static/js/js-map-label.js" async defer></script>
...
</body>
有时会引发此错误:
js-map-label.js:13 Uncaught ReferenceError: google is not defined
at js-map-label.js:13
at js-map-label.js:16
使用defer
,文件是异步下载的,但仅在文档解析完成后才执行。此外,使用 defer 时,脚本将按照与它们被调用的顺序相同的顺序执行。这使得当一个脚本依赖于另一个脚本时 defer 属性的选择。
使用 async
,文件会异步下载,然后在下载后立即执行。
在您的情况下,您可以使用 defer
以便在文档解析完成时执行 javascript,但 不 async
如果您需要依赖项待保留:
<script src="https://maps.googleapis.com/maps/api/js?key=__MY_KEY_HERE__...." defer></script>
<script src="/static/js/js-map-label.js" defer></script>
实际上,延迟用于需要整个 DOM and/or 它们的相对执行顺序很重要的脚本。异步用于独立脚本,如计数器或广告。而且它们的相对执行顺序无关紧要。
来自规范:https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#attr-script-async
The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.
因此,如果您同时使用这两种现代浏览器,则只会执行异步操作,而不会保留执行顺序。
我有 2 个脚本,它们应该 运行 带有异步延迟。但问题是第二个脚本依赖于第一个脚本。 js-map-label.js
需要 运行 只有在 googleapis
已经加载并且 运行ning 之后。使用此设置,它在 80% 的时间内都有效。但有时它不会 运行,所以我不得不一遍又一遍地刷新,直到 js-map-label.js
运行。有什么办法可以解决这个问题吗?
我有这些脚本的顺序:
...
<script src="https://maps.googleapis.com/maps/api/js?key=__MY_KEY_HERE__...." async defer></script>
<script src="/static/js/js-map-label.js" async defer></script>
...
</body>
有时会引发此错误:
js-map-label.js:13 Uncaught ReferenceError: google is not defined
at js-map-label.js:13
at js-map-label.js:16
使用defer
,文件是异步下载的,但仅在文档解析完成后才执行。此外,使用 defer 时,脚本将按照与它们被调用的顺序相同的顺序执行。这使得当一个脚本依赖于另一个脚本时 defer 属性的选择。
使用 async
,文件会异步下载,然后在下载后立即执行。
在您的情况下,您可以使用 defer
以便在文档解析完成时执行 javascript,但 不 async
如果您需要依赖项待保留:
<script src="https://maps.googleapis.com/maps/api/js?key=__MY_KEY_HERE__...." defer></script>
<script src="/static/js/js-map-label.js" defer></script>
实际上,延迟用于需要整个 DOM and/or 它们的相对执行顺序很重要的脚本。异步用于独立脚本,如计数器或广告。而且它们的相对执行顺序无关紧要。
来自规范:https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#attr-script-async
The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.
因此,如果您同时使用这两种现代浏览器,则只会执行异步操作,而不会保留执行顺序。