Make WordPress Core

Opened 16 months ago

Last modified 16 months ago

#22887 new defect (bug)

JavaScript inserted using "attachment_fields_to_edit" executes too early

Reported by: liviumirea Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 3.5
Component: Media Keywords:
Focuses: Cc:


If I add JavaScript using <script> tags inside the "attachment_fields_to_edit" filter, the script is in certain situations executed before the rest of the HTML is added to the DOM. This is troublesome if I want to do something with the HTML I wrote before the <script> tag.

In WordPress 3.4, the <script> tags were simply added to the DOM along with the rest of the HTML. Now, it seems the <script> tags are extracted from the rest of the HTML and are executed before the HTML is added to the DOM.

A simple example to reproduce the problem:

add_action('attachment_fields_to_edit', 'bug_test', 20, 2);
function bug_test($form_fields, $post) {
	if (!is_array($form_fields)) {
		$form_fields = array();
	$form_fields['bug_test'] = array(
		'label'      => 'Bug test',
		'input'      => 'html',
		'html'       => '
			<div id="bug_test_div"></div>
			<script type="text/javascript">alert(jQuery("#bug_test_div").size())</script>
		'value'      => 0

	return $form_fields;

This should always pop a message box containing "1" (i.e. the number of elements found with the "bug_test_div" id), but it doesn't in the following situation:

Access the admin panel, add a new post and click on the "Add Media" button. Upload an image and you will get a message box saying "1". Good. Now upload another image and select it. Now you'll get "0" instead of "1". Select the previous image or any other image and you will still get "0" instead of "1".

Note that this works without a problem (i.e. always outputs "1") in the "Admin panel -> Media -> Edit Media" pages.

Change History (1)

comment:1 wonderboymusic16 months ago

Yep. I am actually still using Thickbox for my custom media stuff because of it. I may just rewrite my code to deal, but I can confirm the problem.

I think if this is happening in a Backbone view, it is because a cached jQuery instance is being stuffed with the data (which will fire the script) before it is inserted into the view's content.

Note: See TracTickets for help on using tickets.