Inject external javascript file in html body after page load

安稳与你 提交于 2019-12-12 13:15:01

问题


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.

thanks, Bilal


回答1:


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

<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>



回答2:


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

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

Courtsey




回答3:


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

Then Run what is implemented in that script




回答4:


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




回答5:


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:

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


来源:https://stackoverflow.com/questions/10734968/inject-external-javascript-file-in-html-body-after-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!