Posted by: Stephen Gray 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});
$.getScript(MVCRoot+fileName+'.js');
$.ajaxSetup({async: true});
[...] Dynamically Load JavaScript With jQuery Another wordpress blogger, Stephen at colourgrey.wordpress.com 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
});
13 January, 2009 at 8:18 pm
Great yet simple. Very helpful. Thanks!