Skip to main content

Bug Tracker

Side navigation

#5018 closed bug (worksforme)

Opened August 06, 2009 07:24AM UTC

Closed October 28, 2010 04:38AM UTC

Last modified August 11, 2012 06:19PM UTC

Javascript Exectuion order when using replaceWith

Reported by: keithpitt Owned by:
Priority: minor Milestone: 1.4
Component: core Version: 1.4.3
Keywords: eval order replaceWith Cc:
Blocked by: Blocking:
Description

I have attached an example of the bug with the ticket. In a nutshell, when I have script tags in a replaceWith call, there is a script execution issue. It's almost like the method executes the javascript first then inserts the new dom into the html.

$('#test').replaceWith("<div id='text'><div id='stale'></div><script type='text/javascript'>$(document).ready(function() { someMethod(); });<" + "/script></div>");

The script there will be executed BEFORE the div's have been inserted into the html.

In the example I provide, hitting the "Break" button should insert the new divs into the page, and insert the word "smelly" into to #stale div - however it inserts it into the OLD #stale div and the new #stale div goes untouched.

Attachments (1)
  • test.html (0.9 KB) - added by keithpitt August 06, 2009 07:24AM UTC.
Change History (4)

Changed September 01, 2009 06:30AM UTC by keithpitt comment:1

No love with this one?

Changed September 14, 2009 06:37PM UTC by flesler comment:2

cc: → keithpitt
priority: blockerminor

Changed October 28, 2010 04:38AM UTC by addyosmani comment:3

cc: keithpitt
resolution: → worksforme
status: newclosed
version: 1.3.21.4.3

With jQuery 1.4.3, I notice that the divs/html content actually appears to be appended to the DOM *before* you notice the JavaScript execute Live Test Case. The reason your javascript is executing is because you're effectively calling a self-executing function inside of a valid script tag. For example, if calling alert('hello'), once the HTML with your inline script tags has been appended, you'll experience the same behavior as if you had simple created a new file, pasted your content in and run it - the self-executing function would still run. This is the expected behavior. If you would rather it not do this, simply structure your code in a way that a function may be defined inside the script tag, but only gets called when you actually want it to.

Changed August 11, 2012 06:19PM UTC by anonymous comment:4

yes i have noticed the same.

here an example:

http://jsfiddle.net/jDMFQ/

the console.log is called twice.