Ticket #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: | |
| Blocking: | Blocked by: |
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
Change History
comment:3 Changed 3 years ago by addyosmani
- Cc keithpitt removed
- Status changed from new to closed
- Version changed from 1.3.2 to 1.4.3
- Resolution set to worksforme
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.
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

