Is it possible to load new Javascript files with AJAX?
I'm building a new AJAX powered website with distinct sections. Each section requires a new set of Javascript functions to ru开发者_如何学JAVAn. I'd rather not load every script at the start, as there might be quite a few.
Is there a way to load new scripts using AJAX and remove old ones (so as to make sure there are no compatibility issues with similar variable names or function signatures).
Thanks
Edit - JQuery is fine, it doesn't have to be old school Javascript
jQuery makes it pretty simple.
$.getScript('myscript.js', function() {
console.debug('Script loaded.');
});
If you can't use jQuery, there's a few more lines to write.
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
script.src = 'myscript.js';
head.appendChild(script);
Three things:
1) Yes, you can load new scripts. You don't even need AJAX in the XHR sense - simply include the script tag in your page dynamically. jQuery provides $.getScript() for things like this, or you can simply create a script element and append it to the head of your document. There are a gazillion examples if you google it.
2) Regarding removing the old (and conflicts, etc). Assuming you have control over these function names, just namespace them properly:
window.myapp = {};
window.myapp.mysection = {};
window.myapp.myothersection = {};
window.myapp.mysection.myfunction = function(){}
Then you don't have to worry about conflicts.
3) Be careful about this. The overhead of loading all those scripts on-demand might be more than just compressing and loading the whole thing in one shot anyway.
Script elements are also a part of the DOM tree, you can attach and remove as you like.
Yes you can use oldschool Javascript.
function addScript(src) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
document.getElementsByTagName('head')[0].appendChild(s);
return s; // to remove it later
}
Once a script is loaded, you can remove the tag again (with removeChild), for example, when you load a new section. That's the reason for the return statement at the end of my function. I'm not really certain it is even useful.
You can add an "onload" attribute to get a warning via a callback when the script is fully loaded, though that probably isn't very cross-platform.
For loading new scripts you should check out LABjs
Unloading them is however not possible, see another StackOverflow post on this issue.
Just Google JavaScript on Demand
http://www.google.ca/search?sourceid=chrome&ie=UTF-8&q=javascript+on+demand
For example, jQuery provides $.getScript(), see http://api.jquery.com/jQuery.getScript/
I've never try it before... but, you can try call a php form with ajax and add the new javascript to a div in body element.. I hope it'll work..
精彩评论