Reputation: 68820
$.ajax({ url: "plugin.js", dataType: 'script', cache: true, success: function() {
alert('loaded');
}});
1) I can't get the script to load, probably due to incorrect path, but how do I determine the correct path? The above code is in init.js, plugin.js is also in the same folder.
2) Can I load multiple plugins at once with the same request? eg. plugin.js, anotherplugin.js?
root
|
|_ html > page.html
|
|_ static > js > init.js, plugin.js
Thanks for your help
Upvotes: 1
Views: 15059
Reputation: 4265
You can use '../'
to set the script path as base path. Then add the relative path for the
$.getScript("../plugin.js").done(function(script, textStatus ) {
alert("loaded:" + textStatus);
}).fail(function(script, textStatus ) {
alert("failed: " + textStatus);
});
Upvotes: 0
Reputation: 3603
As an update, the better way to do this with jQuery 1.9.x is to use Deferreds-methods (i.e. $.when), such as follows:
$.when(
$.getScript('url/lib.js'),
$.getScript('url/lib2.js')
).done(function() {
console.log('done');
})
The .done()
callback function has a number of useful params.
Read the documentation: http://api.jquery.com/jQuery.when/
Upvotes: 1
Reputation: 14883
1) The path will be relative to the page it's loaded from (not the path of your init script) since that's the url the browser will be at when it executes the ajax request.
Edit: Based on your edit, the path to load your script from is either /static/js/plugin.js
(if it'll be deployed at the root of your domain), or ../static/js/plugin.js
to be safe (assuming all pages that it'll be loaded from will be in /html
).
2) No. If they're in different files, they'll need to be different requests. You could merge them into one file on the server-side though...
Upvotes: 3
Reputation: 490657
I would check Firebug's net tab to see if it was loaded correctly, and the path it is trying to load from.
The path will be from the document where the JavaScript was included.
I also keep a config object like this (PHP in this example)
var config = { basePath: '<?php echo BASE_PATH; ?>' };
Then you could do
var request = config.basePath + 'path/to/whatever.js';
Upvotes: 0
Reputation: 28721
You need to use getScript, not ajax. Ajax is for loading data, not for executing code.
If you need to load multiple files, try something like this:
var scripts = ['plugin.js', 'test.js'];
for(var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function() {
alert('script loaded');
});
}
Upvotes: 5
Reputation: 91983
Check out the jQuery .getScript function, which will load the script and include it in the current document.
1) The path should be /static/js/plugin.js
, relative to your document.
2) No. Each file is loaded by a single HTTP request.
Upvotes: 0