Search code examples
javascriptjqueryajaxgetscript

Jquery getScript (after ajax call) uses 100% CPU


I am loading a post via ajax in a page that has several scripts I need already on it. I needed to reload these scripts and originally placed them in the ajax page being called, but realized (because of a chrome console warning) that this is a no-no, so I am trying to use the proper(?) method and load my scripts using jQuery.getScript after my ajax call has completed (getting notified by .ajaxComplete).

When I try to load my scripts (see code below), it seems to work, but I get an ENDLESS series of "success" messages in some kind of loop from hell in my console, until my machine is using close to 100% CPU and I need to force quit my browser.

Any ideas what is causing this? Thanks!

jQuery(document).ready(function(){

  jQuery.ajaxSetup({cache:false});
  jQuery(".post-link").click(function(){
    var post_link = $(this).attr("href");

    jQuery("#single-post-container").html("content loading");
    jQuery("#single-post-container").load(post_link);

    jQuery( document ).ajaxComplete(function() {
      jQuery( ".log" ).text( "Triggered ajaxComplete handler." );
      jQuery.getScript( "scriptone.js" )
      .done(function( script, textStatus ) {
        console.log( textStatus );
      })
      .fail(function( jqxhr, settings, exception ) {
        jQuery( "div.log" ).text( "Triggered ajaxError handler." );
      });
      jQuery.getScript( "scripttwo.js" )
      .done(function( script, textStatus ) {
        console.log( textStatus );
      })
      .fail(function( jqxhr, settings, exception ) {
        jQuery( "div.log" ).text( "Triggered ajaxError handler." );
      });

    });

    return false;
  });

Solution

  • Your ajaxComplete function executes every time an ajax call is made. It, itself contains ajax calls which will all trigger this ajaxComplete function which contains ajax calls which will all trigger this ajaxComplete function which contains ajax calls which will all trigger this ajaxComplete function which contains ajax calls which will all trigger this ajaxComplete function which contains ajax calls which will all trigger this ajaxComplete function which contains ajax calls which will all trigger this ajaxComplete function which contains ajax calls which will all trigger this ajaxComplete function which contains ajax calls which will all trigger this ajaxComplete function which...

    it's infinite recursion, not a loop. don't put ajax in your ajaxComplete function.