Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Ajax $.getScript() method

Tags:

jquery

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

like image 971
SpikETidE Avatar asked Jun 10 '26 04:06

SpikETidE


2 Answers

$.getScript will load and execute Javascript. If you want to just load the Javascript, you will have to put the Javascript in a function, and then execute that function when a future event occurs.

suppose you call:

$.getScript('http://example.com/hello.js');

and it contains the following:

function Hello() {
  alert('hello');
}

The Javascript will be executed, but since the alert is in the function it won't be ran. It won't run until you call the function Hello(). So for the second part, suppose you want to wire it so that when a link is clicked the Hello() function runs. You can provide a callback to run after the Javascript is loaded. So you could do this:

$.getScript('http://example.com/hello.js', function() { Hello(); });

After the script is loaded, that will set a click event handler on your links which will call the Hello function.

like image 162
Lance Fisher Avatar answered Jun 20 '26 16:06

Lance Fisher


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.

like image 32
Anthony Avatar answered Jun 20 '26 17:06

Anthony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!