測試頁:https://jsfiddle.net/y25rk55w/不能腳本加載到iframe中
在這個測試頁面,您可以看到內嵌到對方3 的。每個包含一個<script>
標記,其標記爲<head>
。
問題是:只有<script>
中的第一個將被瀏覽器加載。另外兩個<script>
標籤將出現在dom中,但瀏覽器永遠不會嘗試加載它們。問題不是瀏覽器特定的,它可以在Chrome,Firefox中重新生成。通過添加超時或在追加腳本之前等待,無法解決問題。所有iframe都有編程式生成的內容似乎很重要;如果用帶實際src鏈接的iframe替換此iframe,問題將消失。
問題是:我怎麼能實際加載腳本到iframes 2和3?
完整的測試代碼:
// It doesn't matter if the scripts exist or not
// Browser won't try to load them either way
var scripts = [
'//testdomain.test/script1.js',
'//testdomain.test/script2.js',
'//testdomain.test/script3.js'
];
function createIFrame(win, onCreated) {
var iframe = win.document.createElement('iframe');
iframe.onload = function() {
onCreated(iframe);
};
win.document.body.appendChild(iframe);
}
function loadScript(win, url) {
var script = win.document.createElement('script');
script.src = url;
script.onload = function() {
console.log("Script " + url + " is loaded.");
};
win.document.getElementsByTagName('head')[0].appendChild(script);
}
createIFrame(window, function(iframe1) {
loadScript(iframe1.contentWindow, scripts[0]);
createIFrame(iframe1.contentWindow, function (iframe2) {
loadScript(iframe2.contentWindow, scripts[1]);
createIFrame(iframe2.contentWindow, function (iframe3) {
loadScript(iframe3.contentWindow, scripts[2]);
});
});
});
您在控制檯中遇到什麼錯誤? – putvande