如何仅在加载延迟的Javascript外部文件后执行Javascript?
我想推迟加载外部Javascript文件,直到页面加载完毕(如果无法加载这些外部资源,我也不想阻止渲染)。所以我有这条线如何仅在加载延迟的Javascript外部文件后执行Javascript?,javascript,resources,external,onload,Javascript,Resources,External,Onload,我想推迟加载外部Javascript文件,直到页面加载完毕(如果无法加载这些外部资源,我也不想阻止渲染)。所以我有这条线 <script type="text/javascript" src=“//external.otherdomain.com/path/js/myresoures.js" defer></script> 您可以使用jQuery的$(window.load() 请参阅:这可以通过onload功能实现 您可以动态加载每个。。。这个例子就是从这个例子中提取
<script type="text/javascript" src=“//external.otherdomain.com/path/js/myresoures.js" defer></script>
您可以使用jQuery的$(window.load()代码>
请参阅:这可以通过onload功能实现
您可以动态加载每个。。。这个例子就是从这个例子中提取出来的。它将在您调用的脚本上方插入外部资源importScript()
,然后在加载后启动回调
sSrc
=您的外部脚本,fOnload
=回调
function importScript (sSrc, fOnload) {
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.defer = true;
if (fOnload) { oScript.onload = fOnload; }
document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
oScript.src = sSrc;
}
用法:
importScript("//external.otherdomain.com/path/js/myresoures.js", function () { _satellite.pageBottom(); });
或者,如果jQuery是一个选项,请使用如下命令:
这两个选项中的任何一个都可以在页面末尾的
中使用,就像他们说的那样,在折叠之后,确保首先加载整个DOM。jQuery的getScript不会延迟加载资源。
importScript("//external.otherdomain.com/path/js/myresoures.js", function () { _satellite.pageBottom(); });
$.getScript( "//external.otherdomain.com/path/js/myresoures.js", function () {_satellite.pageBottom();} );