I'm building a new AJAX powered website with distinct sections. Each section requires a new set of Javascript functions to run. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With