SpikETidE SpikETidE - 6 months ago 23
jQuery Question

Jquery Ajax $.getScript() method

$.getScript of Jquery's ajax methods can be used to load and execute javascript from remote location...
Can it also be used to just load the javascript and execute it later when some event occurs on elements that have been loaded using ajax based on some user action...?

Thanks and Regards....

Answer

Is the goal to have the script bind to the elements that have not yet loaded or to lower the number of calls to the remote script?

If it's the first, you don't need to save the script for later executions, you simply need to put the $.getScript() into another function, and bind the events you want to that function:

function executeScript() {
     $.getScript("somescript.js", 
          blah blah blah
          );
 }

$(".post_loaded_elements").hover(executeScript);

However, if the script is on some remote server and you don't want to make a remote call every time a user hovers over an element, you probably need to use some sort of serialization method, where you would request the contents of the script using another ajax method, and de-serialize it and run it. This would use the same setup as the above, only with an extra step of retrieving the script and serializing it into a variable that gets de-serialized in the function. I'll do a quick check to see if serialization is fairly simply in jquery.