From ad1cef94bf134ff7f471a0649dac0158a481cd5d Mon Sep 17 00:00:00 2001
From: John Resig <jeresig@gmail.com>
Date: Mon, 1 Oct 2007 20:15:20 +0000
Subject: [PATCH] A fix for bug #1443, where globalEval occurred
 asynchronously in Safari 2, provided by Andrea Giammarchi.

---
 src/core.js       |   20 ++++++++++++--------
 test/unit/core.js |   11 +++++++++--
 2 files changed, 21 insertions(+), 10 deletions(-)

diff --git a/src/core.js b/src/core.js
index 3b0c465..0cf0444 100644
--- a/src/core.js
+++ b/src/core.js
@@ -564,15 +564,19 @@ jQuery.extend({
 		data = jQuery.trim( data );
 
 		if ( data ) {
-			if ( window.execScript )
-				window.execScript( data );
-
-			else if ( jQuery.browser.safari )
-				// safari doesn't provide a synchronous global eval
-				window.setTimeout( data, 0 );
-
+			// Inspired by code by Andrea Giammarchi
+			// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
+			var head = document.getElementsByTagName("head")[0] || document.documentElement,
+				script = document.createElement("script");
+
+			script.type = "text/javascript";
+			if ( jQuery.browser.msie )
+				script.text = data;
 			else
-				eval.call( window, data );
+				script.appendChild( document.createTextNode( data ) );
+
+			head.appendChild( script );
+			head.removeChild( script );
 		}
 	},
 
diff --git a/test/unit/core.js b/test/unit/core.js
index 730e18c..32ff83e 100644
--- a/test/unit/core.js
+++ b/test/unit/core.js
@@ -123,11 +123,18 @@ test("isFunction", function() {
 	});
 });
 
+var foo = false;
+
 test("$('html')", function() {
-	expect(2);
+	expect(4);
 	
 	reset();
-	ok( $("<script>var foo='test';</script>")[0], "Creating a script" );
+	foo = false;
+	var s = $("<script>var foo='test';</script>")[0];
+	ok( s, "Creating a script" );
+	ok( !foo, "Make sure the script wasn't executed prematurely" );
+	$("body").append(s);
+	ok( foo, "Executing a scripts contents in the right context" );
 	
 	reset();
 	ok( $("<link rel='stylesheet'/>")[0], "Creating a link" );
-- 
1.7.10.4