Stephen's dev blog

jQuery loading remote/external javascript files using getScript()

Posted on: 22 September, 2008

I’ve been working over the weekend on a site and I got to the part of writing the client side MVC using jQuery (because I love the idea now!).

I found out that jQuery has a nice little method for loading external scripts into the page at run time called getScript(). It basically gets the contents of the external file using an AJAX request and then eval()s the code at runtime, which seems like a perfect way of doing it. I reckon it’s much better than appending new <script> tags to the <head> tag as well.

The only issue is that it can take some time to load an external file so you can’t always run functions from within that file straight away. Thankfully there is a workaround for this using another jQuery method. You basically set all AJAX request to be synchronous before you run getScript() and then set AJAX requests to be asynchronous again after the script is loaded. If you end up loading like 20 files at the beginning of a page load this could take a while but hopefully you won’t be doing that 😛

$.ajaxSetup({async: false});
$.ajaxSetup({async: true});

And here’s some more info on this lovely little function 🙂


4 Responses to "jQuery loading remote/external javascript files using getScript()"

Great yet simple. Very helpful. Thanks!

[…] Dynamically Load JavaScript With jQuery Another wordpress blogger, Stephen at has an excellent article on dynamically loading javascript with jQuery. […]

That’s what the callback function is for:

$.getsScript('myscript.js', function() {
// Call functions from myscript.js here

Hi Michael,

Thanks for the tip. As always the jQuery devs had thought this one through and unfortunately I’d not thought about using the callback!


Comments are closed.


  • None
  • Patrick: I changed my code, but now I have another problem: Fatal error: Call to a member function isAvailable() on a non-object in /var/www/vhost/web/shopA
  • Stephen Gray: Hi Patrick, That first error is my fault. I had the method name for the refund() method as void() as I had copied the code from the other method!
  • Patrick: Hi Stephen, thanks for sharing your knowledge about creating a custom payment module. I need an extension for magento to handle a credit card payme


%d bloggers like this: