Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 720
Nick Brunt Avatar asked May 17 '11 13:05

Nick Brunt


3 Answers

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);
like image 67
scurker Avatar answered Nov 14 '22 20:11

scurker


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.

like image 25
jvenema Avatar answered Nov 14 '22 20:11

jvenema


Script elements are also a part of the DOM tree, you can attach and remove as you like.

like image 33
Cem Kalyoncu Avatar answered Nov 14 '22 20:11

Cem Kalyoncu