4

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=“//external.otherdomain.com/path/js/myresoures.js" 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

2 Answers 2

1

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

Usage:

importScript("//external.otherdomain.com/path/js/myresoures.js", function () { _satellite.pageBottom(); });

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

$.getScript( "//external.otherdomain.com/path/js/myresoures.js", 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.

Sign up to request clarification or add additional context in comments.

1 Comment

jQuery's getScript does not load the resource as deferred.
0

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

see: http://api.jquery.com/load/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.