Wednesday, 20 July 2011

Dynamically include JS file throght JQuery

JQuery has a 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. 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.

$.ajaxSetup({async: false});
$.getScript(http://abc.com/scripts/xyz.js');
$.ajaxSetup({async: true});

No comments:

Post a Comment