加载异步资源后运行内联脚本 [英] Run inline script after loading async resources
问题描述
我用优化程序测试了我的页面,建议我对我使用的所有CDN源使用 async
属性,例如:
I tested my page with an optimizer, and it suggests me to use the async
attribute for all CDN sources that I use, like for instance:
<script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
要运行我使用的任何脚本,请执行以下操作:
To run any script I use:
(function(){
})();
我在内联 script
标记中也有引用此类库的JavaScript代码.但是,当我如上所述添加 async
时,在以下脚本中出现错误:
I also have JavaScript code in inline script
tags that reference such libraries. However, when I add async
as above, I get an error in the following script:
<script>
(function(){
jQuery.foundation();
ReactDOM.render(<App />,document.querySelector('#app'));
})();
</script>
我也尝试将 async
添加到此 script
标记中,但是仍然无法正常工作.我仍然收到一个错误,提示使用 async
属性加载的库不存在.
I've tried adding async
to this script
tag as well, but it still doesn't work. I still get an error that the library loaded with the async
attribute doesn't exist.
推荐答案
将代码包装在以下位置:
Wrapping your code in:
(function () {
})();
...不会延迟其执行.要在资源加载之前延迟脚本,请等待窗口 load
事件:
... does not delay its execution. To delay your script until resources have been loaded, wait to the window load
event:
在文档加载过程结束时触发加载事件.此时,文档中的所有对象都在DOM中,并且所有图像, 脚本 ,链接和子框架均已加载完毕.
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
下面是一个使用< script async>
元素加载jQuery并通过内嵌脚本显示jQuery版本的示例:
Here is an example that loads jQuery with a <script async>
element, and shows the jQuery version via the inline script:
window.addEventListener('load', function () {
console.log(jQuery.fn.jquery);
});
<script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
要在加载特定 async
脚本后捕获事件,可以监听其自身的 load
事件.为此,如果您给感兴趣的 script
元素赋予 id
,并确保在其后添加内联代码,这可能是最简单的:
To capture the event when a particular async
script has been loaded, you could listen to its own load
event. For that to work it is probably the easiest if you give an id
to the script
element of your interest, and make sure the inline code comes after it:
jq.addEventListener('load', function () {
console.log(jQuery.fn.jquery);
});
<script id="jq" async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
请注意, async
(和 defer
)属性对内联脚本无效:
Note that the async
(and defer
) attributes have no effect on inline scripts:
如果不存在
src
属性,则不能指定defer
和async
属性.
The
defer
andasync
attributes must not be specified if thesrc
attribute is not present.
它们仅对具有 src
属性的 script
元素起作用.
They only have an effect on script
elements that have the src
attribute.
这篇关于加载异步资源后运行内联脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!