Warning: A call to document.write() from an asynchronously-loaded external script was ignored. How is this fixed?

LearningRoR picture LearningRoR · Oct 18, 2011 · Viewed 19k times · Source

In my Ruby on Rails application I am using the Facebox plugin for an Ajax pop up window. I have 2 pages called add_retail_stores/new.html.erb and add_retail_stores/new.js. The new.js page inherits all elements from the new.html.erb page so it looks exactly alike. I have a Google map script on the HTML page that works as it should. But the new.js page that pops up on my different page called add_store_prices.html.erb page(<%= link_to add_retail_store_path, :remote => true %>)

I get the error:

Warning: A call to document.write() from an asynchronously-loaded external script was ignored. Source File: http://localhost:3000/add_store_prices Line: 0

I believe because it's trying to go through 2 functions/scripts. The first one for the Facebox and then the Google script. Anyone know how to handle this error?

EDIT:

I believe the Facebox plugin is using document.write but I am not sure where, perhaps in one of these 2 lines on my page?

new.js:

$.facebox('<%= escape_javascript(render :template => 'business_retail_stores/new.html') %>')
$('#facebox form').data('remote','true');

Answer

Marc B picture Marc B · Oct 18, 2011

Don't use document.write. The script is being loaded asynchronously, which means it's detached from the document parsing state. There is quite literally NO WAY for the JS engine to know WHERE the document.write should be executed in the page.

The external script could load instantaneously and the document.write executes where the <script src="..."> tag is, or it could hit a net.burp and load an hour later, which means the document.write gets tagged at the end of the page. It's quite literally a race condition, so JS engines will ignore document.writes from scripts loaded asynchronously.

Convert the document.write to use regular DOM operations, guarded by a document.onload type handler.