如何判断脚本是否已加载?
我有一个函数,在某个时候document.getElementsbytagname(“ script”)
,并且想知道每个脚本是否已加载。
我想获得一个承诺,如果它已经加载并待定,则可以实现,因此我可以使用。 。
我想我想一个负载事件,但是如果脚本已经加载,我将永远不会得到该事件。
我可以通过做出一些假设来解决这个问题,即我控制所有动态脚本标签,对于静态脚本标签,文档currentscript始终是迄今为止加载的最后一个脚本,并且所有上述脚本都在加载,假设他们是他们的加载。都是静态的。但是这些假设可能并不总是正确的。
因此,是否有一种方法可以检查状态并产生承诺,即取决于状态将以实现(已解决)开始或通过负载事件发射来实现?
I have a function which at some time does document.getElementsByTagName("script")
and it wants to know for each script if it was loaded already.
I'd like to get a Promise which is fulfilled if it was loaded and pending if it's still going on, so I can attach next steps with .then(...)
and be sure they get executed.
I could attach a load event I suppose, but if the script was already loaded, I wouldn't ever get the event.
I could work around this by making some assumptions, namely that I am in control of all dynamic script tags, and for static script tags, the document.currentScript is always the last script loaded so far and all preceding scripts are done loading, assuming they were all static. But those assumptions might not always be true.
So, is there a way to check the status and generate Promise that depending on the status will either start as fulfilled (resolved) or be fulfilled by the load event firing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将脚本元素添加到DOM上会导致它们异步加载,而不是及时及时使用即可使用它们的代码。您需要为脚本的
onload
事件使用回调函数。这是这样做的示例助手函数。Adding script elements to the DOM will cause them to load asynchronously, not in time for code that immediately follows to make use of them. You need to use a callback function for the script's
onload
event. Here is an example helper function that does so.mutationObserver
可用于将加载事件侦听器添加到动态创建的脚本元素中。地图
用于存储加载事件发射时将解决的承诺。开始观察:
定义一个返回承诺的函数,如果脚本尚未加载或解决否则,该函数将待定:
示例用法:
使用
scriptmmap.values()
以获取动态创建脚本的承诺:为了效率,请停止观察何时不再需要:
A
MutationObserver
can be used to add a load event listener to dynamically created script elements.A
Map
is used to store the promises that will be resolved when the load event fires.Start observing:
Define a function that returns a promise that will be pending if a script has not yet loaded or resolved otherwise:
Example usage:
Use
scriptMap.values()
to get the promises of dynamically created scripts:For efficiency's sake, stop observing when it is no longer required: