문제

My site was using jquery.load() to do navigation on a big chunk of the page. I really appreciate the ability to only include only a particular part of the loaded content, here the div with id="content":

$(frame_selector).load(url +" #content", function(response, status, xhr) {...});

But now I need to be able to run scripts that are part of the pages being loaded dynamically. Jquery.load() strips out these scripts, but jquery.ajax() doesn't. So I duplicated the partial-content functionality of jquery.load in an ajax call as such:

$.ajax({
  url: url,
  dataType: 'html', 
  success: function(data, textStatus, XMLHttpRequest) {
      // Only include the response within the #content id element.
      $(frame_selector).html( jQuery("<div>")
            .append(data)
            .find("#content")
      );
  }
});

The problem is that the scripts which are being dynamically loaded from the ajax call aren't running reliably. Sometimes they don't seem to have any effect, perhaps because they're running too early. The scripts are just doing DOM manipulation in jquery -- not relying on images or flash or anything that's not supposed to be loaded yet. To keep from getting stuck I have this hideous hack to get things working. Instead of the AJAX-loaded script just using:

$(document).ready( function() {...} );  // unreliable

I delay the script 200ms before running:

$(document).ready( window.setTimeout( function() {...}, 200 )); // HATE THIS

Anybody know how I can make this work reliably without hard-coding a delay? I'm guessing it's a race condition between the <script> and my logic to load #content into a new div, but I'm not sure what to do about it.

도움이 되었습니까?

해결책

I assume the scripts are doing manipulation upon the DOM elements you're adding through AJAX.

jQuery has an isReady property that it sets once the ready event has been triggered on the page.

Any subsequent calls to jQuery.ready(...) will first check this isReady flag. If the flag is set to true, it will call the handler immediately. You can see why this would cause problems in your code.

One option would be to load the response into a jQuery fragment and parse out all of the <script /> tags for execution later.

var ajaxResponse = $(html);
var scripts = ajaxResponse.find('script');

// Move your scripts into a new element
var tempScripts = $().append(scripts);

// Append your content, followed by your script tags
$(document).append(ajaxResponse);
$(document).append(tempScripts);

다른 팁

@Dan has the answer. When loading scripts via ajax the document isReady is true. This means if this is the script tag that is requested by your ajax request:

<script type="text/javascript">
    if (jQuery.isReady) {
        $('body').append("<div id='new_content'>Document Ready</div>");
    }
    else {
        $('body').append("<div id='new_content'>Document Not Ready</div>");
    }
</script>

Instead of parsing utilize JSON. One property will hold HTML. Another property will hold the scripts.

Then you can do this:

$(document).append(ajaxResponse.html);
$(document).append(ajaxResponse.script);

Also if you load scripts with the ready function surrounding you code it will create a closure. this closure will last the lifetime of the page. Memory leaks will be created every time you request that script without refreshing your page

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top