Reload javascript file after an AJAX request

After the request, the new elements created are not recognized by the event handlers in my jQuery code.

Is there a way to reload the file to re-register these events?

I’m assuming that you mean that events you’ve registered for elements that have been replaced by with the results of your ajax requests aren’t firing?

Use .live() (see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.

e.g.
replace

$('div.someClass').click(function(e){
    //do stuff
});

with

$('div.someClass').live('click', function(e){
    //do stuff
});

Important:

While I’ve recommended using .live() this is for clarity as its syntax is similar to .bind(), you should use .on() if possible. See links in @jbabey’s comment for important information.

This question was about binding event handler on DOM element created after the loading of the page. For instance, if after a request ajax you create a new <div> bloc and want to catch the onClick event.

//This will work for element that are present at the page loading
$('div.someClass').click(function(e){
    //do stuff
});

// This will work for dynamically created element but is deprecated since jquery 1.7
$('div.someClass').live('click', function(e){
    //do stuff
});

// This will work for dynamically created element
$('body').on('click', 'div.someClass', function(e){
    //do stuff
});

You would find the documentation here: http://api.jquery.com/on/

This codes works perfect for me..

$("head script").each(function(){
            var oldScript = this.getAttribute("src");
            $(this).remove();
            var newScript;
            newScript = document.createElement('script');
            newScript.type="text/javascript";
            newScript.src = oldScript;
            document.getElementsByTagName("head")[0].appendChild(newScript);
        });

It removes the old script tag and make a new one with the same src (reloading it).

Read More:   Use of semicolons in ES6 [duplicate]

To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.

For example,

$("#load").click(function(){
    $.getScript('helloworld.js', function() {
        $("#content").html('Javascript is loaded successful!');
    });
});

when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.

Try it yourself
In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.

<html>
<head>

<script type="text/javascript" src="https://stackoverflow.com/questions/8594408/jquery-1.4.2.min.js"></script>

</head>
<body>
  <h1>Load Javascript dynamically with jQuery</h1>

<div id="content"></div>
<br/>

<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>

<script type="text/javascript">

$("#load").click(function(){
  $.getScript('js-example/helloworld.js', function() {
     $("#content").html('
          Javascript is loaded successful! sayHello() function is loaded!
     ');
  });
});

$("#sayHello").click(function(){
  sayHello();
});

</script>
</body>
</html>

simple way to solve this problem

$(document).ready(function(){

$('body').on('click','.someClass',function(){

//do your javascript here..

});
}); 

You can also attach the click handlers to the body so that they never get destroyed in the first place.

$('body').on('click', 'a', function(event) {
  event.preventDefault();
  event.stopPropagation();
  // some stuff
})

In your request callback, call a function that acts on your newly appended or created blocks.

$.ajax({
   success: function(data) {
        $('body').append(data);
        //do your javascript here to act on new blocks
   }
});

  var scripts = document.getElementsByTagName("script");
  for (var i=0;i<scripts.length;i++) {
    if (scripts[i].src)
      if(scripts[i].src.indexOf('nameofyourfile')  > -1 )
        var yourfile = scripts[i].src;
  }
  jQuery.get(yourfile, function(data){
  if(data){
     try {
      eval(data);
     } catch (e) {
     alert(e.message);
    }
 }
    });

You can try loadscript plugin for loading the javascript file.

Read More:   How to check if an item is selected from an HTML drop down list?

forexample 
$("#load").click(function(){
    $.loadScript('path/example.js');
});

or 
$.ajax({
   success: function(data) {
        $.loadScript('path/example.js');
   }
});

http://marcbuils.github.io/jquery.loadscript/

What do you mean not recognized by jQuery?

jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.

What isn’t visible exactly?

P.S.: Reloading JavaScript is possible, but highly discouraged!


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts