Force re-firing of all (scripts / functions) on ajaxed content Force re-firing of all (scripts / functions) on ajaxed content wordpress wordpress

Force re-firing of all (scripts / functions) on ajaxed content


The solution you choose here will have to depend on how the scripts are initialized. There are a couple common possibilities:

  1. The script's actions are evoked immediately upon loading of the script. In this case, the script might look something like this:

    (function() {     console.log('Running script...');})();
  2. The script's actions are evoked in response to some event (such as document ready (JQuery) or window onload (JavaScript) events). In this case, the script might look something like this:

    $(window).on('load', function() {    console.log('Running script...');});

Some options for these two possibilities are considered below.

For scripts that run immediately on loading

One option would be to just remove the <script> elements you want to trigger from the DOM and then reattach them. With JQuery, you could do

$('script').remove().appendTo('html');

Of course, if the above snippet is itself in a <script> tag, then you will create an infinite loop of constantly detaching and re-attaching all the scripts. In addition, there may be some scripts you don't want to re-run. In this case, you can add classes to the scripts to select them either positively or negatively. For instance,

// Positively select scripts with class 'reload-on-ajax'$('script.reload-on-ajax').remove().appendTo('html');// Negatively select scripts with class 'no-reload'$('script').not('no-reload').remove().appendTo('html')

In your case, you would place one of the above snippets in the event handler for AJAX completion. The following example uses a button-click in lieu of an AJAX completion event, but the concept is the same (note that this example doesn't work well within the StackOverflow sandbox, so try loading it as a separate page for the best result):

<html>  <head></head>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  <script class="reload-on-ajax">    console.log('Script after head run.');  </script>  <body>    <button id="reload-scripts-button">Reload Scripts</button>  </body>  <script class="reload-on-ajax">    console.log('Script after body run.');  </script>  <script>     $('#reload-scripts-button').click( () => $('script.reload-on-ajax').remove().appendTo('html') );  </script></html>