Bug Tracker

Opened 13 years ago

Closed 12 years ago

Last modified 10 years ago

#5018 closed bug (worksforme)

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:


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 (926 bytes) - added by keithpitt 13 years ago.

Download all attachments as: .zip

Change History (5)

Changed 13 years ago by keithpitt

Attachment: test.html added

comment:1 Changed 13 years ago by keithpitt

No love with this one?

comment:2 Changed 13 years ago by flesler

Cc: keithpitt added
Priority: blockerminor

comment:3 Changed 12 years ago by addyosmani

Cc: keithpitt removed
Resolution: worksforme
Status: newclosed

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.

comment:4 Changed 10 years ago by anonymous

yes i have noticed the same.

here an example:


the console.log is called twice.

Note: See TracTickets for help on using tickets.