[英]Error: It isn't possible to write into a document from an asynchronously-loaded external script
[英]Warning: A call to document.write() from an asynchronously-loaded external script was ignored. How is this fixed?
在我的Ruby on Rails應用程序中,我使用Facebox插件進行Ajax彈出窗口。 我有2個頁面叫做add_retail_stores/new.html.erb
和add_retail_stores/new.js
new.js
頁面繼承了new.html.erb
頁面中的所有元素,因此它看起來完全相同。 我在HTML頁面上有一個Google地圖腳本,可以正常工作。 但是在我的不同頁面上彈出的new.js
頁面名為add_store_prices.html.erb
頁面( <%= link_to add_retail_store_path, :remote => true %>
)
我收到錯誤:
警告:忽略了從異步加載的外部腳本調用document.write()。 源文件: http:// localhost:3000 / add_store_prices行:0
我相信因為它試圖通過2個函數/腳本。 第一個是Facebox,然后是Google腳本。 有誰知道如何處理這個錯誤?
我相信Facebox插件正在使用document.write
但我不確定在哪里,也許在我的頁面上的這兩行之一?
new.js:
$.facebox('<%= escape_javascript(render :template => 'business_retail_stores/new.html') %>')
$('#facebox form').data('remote','true');
不要使用document.write。 該腳本是異步加載的,這意味着它與文檔解析狀態分離。 對於JS引擎來說,確實知道應該在頁面中執行document.write是非常方便的。
外部腳本可以即時加載,document.write可以在<script src="...">
標簽的位置執行,也可以在net.burp上運行並在一小時后加載,這意味着document.write會被標記為頁面的末尾。 它確實是競爭條件,因此JS引擎將忽略異步加載的腳本中的document.writes。
轉換document.write以使用常規DOM操作,由document.onload
類型處理程序保護。
如果您有權訪問相關的.js文件,那么最好的解決方案是修改“document.write()”方法並將其替換為有意義的方法,以便分發其中包含的內容。
上面已經很好地描述了其原因。
如果您使用document.write將html標記寫入頁面:
document.write("<script src=...></script>");
要么
document.write("<img href=... />");
考慮使用您已經使用的相同類型的異步格式:
// Add/Remove/Sugar these components to taste
script = document.createElement("script");
script.onload = function () { namespaced.func.init(); };
script.src = "http://...";
document.getElementsByTagName("script")[0].parentNode.appendChild(script);
如果您想要附加供用戶查看和交互的DOM元素,那么您最好:
a)按id抓取特定的containter(section / div),並附加你的內容:
document.getElementById("price").innerHTML = "<span>$39.95</span>";
b)在DOM之外構建內容並將其注入容器中:
var frag = document.createDocumentFragment(),
span = document.createElement("span");
span.innerText = "39.95";
frag.appendChild(span);
document.getElementById("price").appendChild(frag);
再次,Sugar符合您的喜好。
如果您無法訪問mod第二個.js文件,我建議您使用它們。
加載谷歌地圖與地方庫有同樣的問題。 我暫時覆蓋了write函數,在頭部創建了一個新的腳本元素。
(function() {
var docWrite = document.write;
document.write = function(text) {
var res = /^<script[^>]*src="([^"]*)"[^>]*><\/script>$/.exec(text);
if (res) {
console.log("Adding script " + res[1]);
var head = document.getElementsByTagName('head')[0];
var script = document.createElement("script");
script.src = res[1];
head.appendChild(script);
} else {
docWrite(text);
}
}
})();
現在我只需要異步加載腳本就可以了
document.write('<script src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.