External JavaScript on Demand With jQuery.getScript()
- Share /
- AJAX, jQuery / 7.28.08 / 15 Comments / /
I find myself using JavaScript more and more often in my work. As work on a particular site grows, I find that too many external scripts begin to pile up in the <head> section of my document, eventually effecting performance. Thanks to jQuery’s $.getScript method, I’ve found an elegant solution to this problem.
Think of jQuery.getScript() as the JavaScript equivalent to CSS’s @import. Take it one step further and use it to load JavaScript only when it is needed and you have a lean combination.
JavaScript / jQuery
if ($('a.email').length > 0){ $.getScript('js/jquery.mailto.js',function(){ $('a.email').mailto(); }); }
How it works
This small snippet of code that will check for the existence of an object, in this case that object is any anchor link with a class of email. If this object is found on a page, a corresponding .js file (js/jquery.mailto.js) will be loaded and a callback function initiated ($(‘a.email’).mailto();). If the object is not found, the script will not be loaded. This assumes that the snippet is enclosed in a document ready event.
I find this approach to be the most elegant when handling multiple jQuery plugins. One could compare it to the @import CSS command that is frequently used to load in multiple style sheets from one master CSS file.
Notes
When loading external scripts dynamically with jQuery’s getScript, a cache busting parameter is added to the request URL. So, instead of writing something like <script src=’/js/foo.js’>, it writes something like <script src=’/js/foo.js?_=ts2477874287′>, causing the script to be pulled anew each time. I assume this is so that calling getScript repeatedly on a single page causes the script to be executed multiple times.
Resources
I originally read about this technique in the book jQuery in Action, which I would highly recommend checking out. I’ve found it to be clearer, easier to read and more powerful than Learning jQuery 1.3. Both have they’re advantages and disadvantages but I prefer jQuery in Action.
















Leandro / 12.1.08 / 11:21 AM
And how to correct the problem with js/foo.js?_=ts2477874287 ?
kevin / 12.1.08 / 11:39 AM
It’s shouldn’t really be a problem depending on how you look at it. That is a random string added automatically by jQuery so that the file being imported is NOT cached. If you want to enable caching you can use this instead of $.getScript():
Funka! / 1.6.09 / 7:10 PM
Hello, I arrived at this article doing a google search for “jquery getscript cache” (searching for a solution to leandro’s same question) but this comment isn’t related to the caching problem, but rather to let you know that your code sample in your reply on december 1 is being borked by an injection of a span tag with id=”high_3″ and class=”searchterm3″ around the word “cache” (in an apparent attempt to highlight my referring search terms) — just FYI!
kevin / 1.13.09 / 9:45 AM
Hey funka,
I’ve done a scan through the source and generated source (after JavaScript) and I can’t seem to find anything labeled “searchterm3″ aside from your comment.
I’m thinking that it could be a Wordpress plugin that is doing this, but I’m not sure how this is causing issues for you?
Glad I could help with the caching issue though.
valery / 6.4.09 / 5:25 AM
I have another problem with $.getScript() function. IE don’t send cookies with script request when domain is different from current.
kevin / 6.5.09 / 8:51 AM
Valery,
I’ve never encountered a situation where a cross domain cookie is being sent, but for more control over the $.getScript method you can actually use the $.ajax method that it is created from. This may allow you to use line by line alert()’s to debug your situation.
Here’s an example I’ve found in the jQuery Google Groups forum that is used to access the Maxmind GeoIP JavaScript API:
To view the full thread visit:
http://groups.google.com/group/jquery-dev/browse_thread/thread/5dc8330bbdb1b4e8
Some of the more seasoned developers there may be able to help you out with your specific cookie issue. Unfortunately I don’t have much advanced knowledge of JavaScript cookies and cross domain requests.
I hope this helps!
Ralph / 7.22.09 / 7:57 AM
Hello friends,
I'm having some trouble getScript with, because isn't works in IE7+. I'm loading others JQuery plugins (jquery.validate, jquery. form) but I have the next error/alert:
Object doesn't support this property or method
At line: 169586387
That line doesn't exists, is fake.
I don't know what is going on, can you help me please?
Cheers!
kevinlearynet / 7.22.09 / 12:57 PM
Hey Ralph,
Can you send me a link to where it's not working?
Ralph / 7.22.09 / 3:36 PM
Sure!
http://www.avandaro.es/clientes/fabrilamp/admin/
Usuario: 123
Password: 123
Go to: "Gestión Puntos De Venta" link, then click on "Nuevo Punto de venta" link and you'll see error on IE.
Thanks
Ralph / 7.23.09 / 4:00 AM
Sure!
http://www.avandaro.es/clientes/fabrilamp/admin/
Usuario: 123
Password: 123
Go to: "Gestión Puntos De Venta" link, then click on "Nuevo Punto de venta" link and you'll see error on IE.
Thanks
Ralph / 7.24.09 / 11:06 PM
Can you help me? Anyone?
kevinlearynet / 7.28.09 / 12:11 AM
Hey Ralph,
I'm unsure what the problem is; but I found a great thread post by a guy named Norbert Dynamically Loaded Scripts in IE 7 – Problems Found and Lessons Learned.
That's a great guide I hope it help's some. Good luck!
kevinlearynet / 7.28.09 / 12:12 AM
Hey Ralph,
I'm unsure what the problem is; but I found a great thread post by a guy named Norbert called Dynamically Loaded Scripts in IE 7 – Problems Found and Lessons Learned.
That's a great guide I hope it help's some. Good luck!
atasözleri / 2.18.10 / 8:16 AM
I dont understand this mean. I want to load external page with using ajax.
Pofff!
Can anyone help me??
kevinlearynet / 3.5.10 / 1:17 PM
Check out the load() method of the jQuery library, I think it should handle what you need (http://api.jquery.com/load/)