From e287007f6a129901a07b6a342d0c7bfa36a7a868 Mon Sep 17 00:00:00 2001 From: John Resig Date: Wed, 17 Oct 2007 22:42:12 +0000 Subject: [PATCH] Added a fix for bug #1698, in which injected scripts were executed out of order, in relation to the DOM. --- src/core.js | 50 +++++++++++++++++++++++++++++------------------ test/unit/core.js | 6 +++++- 2 files changed, 36 insertions(+), 20 deletions(-) diff --git a/src/core.js b/src/core.js index b3b0a9d27..d396ee95a 100644 --- a/src/core.js +++ b/src/core.js @@ -461,39 +461,51 @@ jQuery.fn = jQuery.prototype = { if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) ) obj = this.getElementsByTagName("tbody")[0] || this.appendChild( document.createElement("tbody") ); + var scripts = jQuery( [] ); + jQuery.each(elems, function(){ var elem = clone ? this.cloneNode( true ) : this; - if ( !evalScript( 0, elem ) ) + if ( jQuery.nodeName( elem, "script" ) ) { + + // If scripts are waiting to be executed, wait on this script as well + if ( scripts.length ) + scripts = scripts.add( elem ); + + // If nothing is waiting to be executed, run immediately + else + evalScript( 0, elem ); + + } else { + // Remove any inner scripts for later evaluation + if ( elem.nodeType == 1 ) + scripts = scripts.add( jQuery( "script", elem ).remove() ); + + // Inject the elements into the document callback.call( obj, elem ); + } }); + + scripts.each( evalScript ); }); } }; function evalScript( i, elem ) { - var script = jQuery.nodeName( elem, "script" ); + if ( elem.src ) + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); - if ( script ) { - if ( elem.src ) - jQuery.ajax({ - url: elem.src, - async: false, - dataType: "script" - }); + else + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); - else - jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); - - if ( elem.parentNode ) - elem.parentNode.removeChild( elem ); - - } else if ( elem.nodeType == 1 ) - jQuery( "script", elem ).each( evalScript ); - - return script; + if ( elem.parentNode ) + elem.parentNode.removeChild( elem ); } jQuery.extend = jQuery.fn.extend = function() { diff --git a/test/unit/core.js b/test/unit/core.js index eee1740d6..7280ab900 100644 --- a/test/unit/core.js +++ b/test/unit/core.js @@ -834,8 +834,10 @@ test("val(String)", function() { ok( $("#select1").val() == "3", "Check for modified (via val(String)) value of select element" ); }); +var scriptorder = 0; + test("html(String)", function() { - expect(3); + expect(9); var div = $("div"); div.html("test"); var pass = true; @@ -850,6 +852,8 @@ test("html(String)", function() { $("#main").html('foo
'); + $("#main").html("