页面加载后在 html body 中注入外部 javascript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10734968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:43:04  来源:igfitidea点击:

Inject external javascript file in html body after page load

javascriptjquerymodel-view-controllerdelayed-execution

提问by Tepu

I want to load an external javascript after page is loaded. Actually the javascript contains source for an ad and its making page load slow. All I want is to delay loading & execution of ads to make sure fast page load.

我想在页面加载后加载外部 javascript。实际上,javascript 包含一个广告的源代码,它使页面加载速度变慢。我想要的只是延迟加载和执行广告以确保快速加载页面。

thanks, Bilal

谢谢,比拉尔

回答by Ale? Kotnik

You may just use this script at the last tag of your body block:

您可以在 body 块的最后一个标签处使用此脚本:

<script type="text/javascript">
   var script = document.createElement('script');
   script.setAttribute('src', 'http://yourdomian.com/your_script.js');
   script.setAttribute('type', 'text/javascript');
   document.getElementsByTagName('head')[0].appendChild(script);
</script>

回答by Ankur Verma

var script=document.createElement('script');
script.type='text/javascript';
script.src=url;

$("body").append(script);

Courtsey

考特西

回答by Richard

I would look at using asynchronous Javascript loading. There are frameworks for this such as requireJS.

我会考虑使用异步 Javascript 加载。有这方面的框架,例如requireJS

回答by DadViegas

$("#selector").click(function(){ $.getScript("YourScript.js"); });

$("#selector").click(function(){ $.getScript("YourScript.js"); });

Then Run what is implemented in that script

然后运行该脚本中实现的内容

回答by rainabba

Without using something like jQuery getScript() and a promise or a proper loading library like requireJS, the script can be included in the page, but will load async so there's no guarantee it will be ready when you need it. If you're already using jQuery, the simple answer is then:

如果不使用 jQuery getScript() 之类的东西和 promise 或适当的加载库(如 requireJS),脚本可以包含在页面中,但会加载异步,因此无法保证它会在您需要时准备就绪。如果您已经在使用 jQuery,那么简单的答案是:

$.getScript( scriptUrl ).then( function() {
  //do this ONLY after the script is fully loaded
});