32

Is there any jquery plugin (instead of incldeMany) or simple function to include js-files on demand ?

for example:

$.include('myscript.js'); 

?

Heinrich
  • 751
  • 2
  • 8
  • 6

2 Answers2

63

How about jQuery.getScript()? It's built in to jQuery and works like so:

$.getScript('ajax/test.js', function() {
    alert('Load was performed.');
});
Olly Hodgson
  • 15,076
  • 3
  • 40
  • 60
  • 3
    Note: the path is relative to the root folder, not where the jQuery file is. So, if you have a main file for your functions like site.com/assets/main.js and you use this function to load in "test.js" the function would be: $.getScript('assets/test.js', function() { alert('Load was performed.'); }); or wherever you've got the file. Hope this helps! – Drew Dello Stritto Mar 22 '13 at 05:34
  • 5
    @DrewDelloStritto The path is not relative to the root folder but to the folder where the browser called html file is. So if you load site.com/assets/page.html and the main script is in site.com/assets/main.js than to load test in the same folder you need `$.getScript('test.js', function() { alert('Load was performed.'); });` – Alepac Apr 27 '13 at 05:08
  • Note that `alert()` might not always be fired. See https://stackoverflow.com/a/19819672/13019 for a good solution. – Olly Hodgson Aug 16 '19 at 03:01
3

Not exactly a jQuery plugin, but you might try looking into RequireJS. Especially the "How to use RequireJS with jQuery" section.

I don't have much experience with this solution yet, but from what I've read and played around with I like the possibilities.

Aaron Wagner
  • 5,739
  • 1
  • 31
  • 38