Loading External JavaScript with JavaScript

For whatever the reason, it comes in handy to be able to load in JavaScript with JavaScript. I’ve found four different ways to do this, each with its own pros and cons. I’ll let you make the call as to which one works best for you.

Method 1: Document.Write


document.write('<scr'+'ipt src="/js/somefile.js"></scr'+'ipt>');

Pros

  • Really easy
  • No external library
  • Simple to understand what’s going on
  • Easy to put in just the right spot on the page.

Cons

  • document.write doesn’t fire until the end of the page load
  • Timing issues
  • You can’t seem to access variables and functions inside the external file with your document’s JavaScript.
  • Make sure you break up those script tags. Some browsers are confused by them, even if they’re in a string.

Method 2: jQuery’s getScript


$.getScript('/js/somefile.js', function(){

//Functionality to run after the JS is loaded.

});

Pros

  • Simple
  • Allows you to specify functionality to run after the file is loaded.
  • Functions and variables in the external file are now in the DOM.

Cons

  • Requires external library (jQuery)
  • Does not work on off-domain files (AJAX calls cannot be made cross-domain).

Method 3: Updating Existing Script Tag


<script src="" id="dynamicScript"></script>
<script>
   dynamicScript.src="/js/somefile.js"
</script>

Pros

  • Really easy
  • No external library
  • Simple to understand what’s going on
  • Easy to put in just the right spot on the page.

Cons

  • Requires an existing <script> tag on the page.
  • Timing issues
  • You can’t seem to access variables and functions inside the external file with your document’s JavaScript.
  • Make sure you break up those script tags. Some browsers are confused by them, even if they’re in a string.

Method 4: Script Object


var docHead = document.getElementsByTagName('head').item(0);
var newScript= document.createElement("script");
newScript.src="/js/somefile.js";
newScript.type = "text/javascript";
docHead.appendChild( newScript );

Pros

  • Cross-domain safe
  • Loads functions and variables into DOM
  • No external library needed.

Cons

  • Can be complex
  • Sometimes hard to debug
  • No code block to set aside to execute after load.

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.