8

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

Tepu
  • 1,602
  • 2
  • 20
  • 28

5 Answers5

22

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>
Aleš Kotnik
  • 2,654
  • 20
  • 17
6
var script=document.createElement('script');
script.type='text/javascript';
script.src=url;

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

Courtsey

Community
  • 1
  • 1
Ankur Verma
  • 5,793
  • 12
  • 57
  • 93
  • 5
    There is no need to use jQuery at this point. `document.body.appendChild(script);` – Tomalak May 24 '12 at 09:54
  • this will not show ads that are loaded by the external script. – Tepu May 24 '12 at 10:44
  • 1
    The script does not become immediately available (using the jQuery and non-jQuery approaches) so this isn't a universal solution. You would either need to use a library like async or use the jQuery getScript method with a promise (see below). – rainabba May 23 '15 at 18:42
2

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

Jon Adams
  • 24,464
  • 18
  • 82
  • 120
Richard
  • 21,728
  • 13
  • 62
  • 101
2

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

Then Run what is implemented in that script

DadViegas
  • 2,263
  • 16
  • 12
  • Same as above, this loads async so to be stable, you must use an sync library or promises for example: $.getScript( url ).then( function() { //won't be called until the script is actually loaded }); – rainabba May 23 '15 at 18:39
0

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
});
rainabba
  • 3,804
  • 35
  • 35