How do I execute Javascript only after a deferred Javascript external file has loaded?

I want to defer loading of an external Javascript file until the page has loaded (and also I don’t want to block rendering if those external resources cannot be loaded). So I have this line

<script type="text/javascript" src=“//" defer></script>

However, when this file does eventually load, I want to run the following …

<script type="text/javascript">_satellite.pageBottom();</script>

However, as is, the above may run before the script has loaded. How do I run the above (or any) Javascript only after a remote resource has loaded? Keep in mind that if the external resource doesn’t load (it times out, for example), I don’t want to run the Javascript.

Thanks, - Dave



This can be achieved by an onload function.

You can dynamically load each... This example is pulled right from MDN. It will insert your external resource above the script you call importScript() then launch the callback after loading.

sSrc = your external script, fOnload = the callback

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("//", function () { _satellite.pageBottom(); });

Or if jQuery is an option, use .getScript() like so:

$.getScript( "//", function () {_satellite.pageBottom();} );

Either of these options can be used in a <script> at the end of the page, after the fold as they say, ensuring the entire DOM loads first.


how bout that?:

oh my body has no enough characters


You can use jQuery's $(window).load();



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.