32

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

for example:

$.include('myscript.js'); 

?

2 Answers 2

63

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

$.getScript('ajax/test.js', function() {
    alert('Load was performed.');
});
Sign up to request clarification or add additional context in comments.

3 Comments

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!
@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.'); });
Note that alert() might not always be fired. See stackoverflow.com/a/19819672/13019 for a good solution.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.