views:

95

answers:

4
$.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

+1  A: 

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...

Alconja
Thanks, I've edited the desc to show the structure, can you help find the path? Thanks!
Nimbuz
Tried both /static/js/plugin.js and /static/js/plugin.js but it still won't load. Any other way of cross-checking?
Nimbuz
Alconja
A: 

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.

Emil Vikström
Tried both /static/js/plugin.js and /static/js/plugin.js but it still won't load. Any other way of cross-checking the path?
Nimbuz
Use Firefox when developing. Install Firebug (plugin) which is free. Inside that, activate all "debug panels" and place a "breakpoint" where you need to stop the javascript. Then you can mouse-over on the active variables and read their current value. Quite nice!
BerggreenDK
+1  A: 

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');
  });
}
Ben Rowe
From the docs: `getScript` is shorthand for `$.ajax({ url: url, dataType: 'script', success: success });`, so there's nothing wrong with using `.ajax`, it's just a bit more verbose.
Alconja
I'm using .ajax specifically for asynchronous caching (cache: true).
Nimbuz
A: 

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';
alex