最终更新:第二个代码块正在运行 - 我只是错过了输入网址。
我试图将动态创建的脚本放入iframe中。我可以访问iframe的头部,但它似乎不接受附加请求。控制台日志调用返回head标记,并且以下文本追加到正文中工作正常。我还尝试将脚本标记附加到正文中。 (注意:脚本标记不在同一个域中,因此我避免使用getScript或ajax)。
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head")); // outputs: [<head></head>]
$(this).contents().find("head").append(script); // doesn't work
$(this).contents().find("body").append(script); // doesn't work
$(this).contents().find("body").append("Test"); // works
}).appendTo("#content");
});
以下是基于以下建议成功附加脚本的新版本,但脚本未进行评估(通过简单警报测试)。另外,另一个奇怪的是:&#34;工作&#34;图标显示约15秒,状态(以铬合金形式显示)&#34;检索...&#34;最终它会停止,但没有任何反应。
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head"));
$(this).contents().find("head")[0].appendChild(script);
$(this).contents().find("body").append("Test");
}).appendTo("#content");
});
更新:当光标图标最终完成工作时(大约10秒,这很奇怪,因为它是一个带有一行代码的本地服务器),我在Chrome控制台中收到此消息(它已经在所有红色都带有红色圆圈&#34; X&#34;旁边的图标):
GET http://cross-domain.com/script.js
(anonymous function)temp.html:16
jQuery.event.dispatchjquery-1.7.1.js:3261
jQuery.event.add.elemData.handle.eventHandlejquery-1.7.1.js:2880
jQuery.fn.extend.appendjquery-1.7.1.js:5771
jQuery.fn.extend.domManipjquery-1.7.1.js:5973
jQuery.fn.extend.appendjquery-1.7.1.js:5769
jQuery.each.jQuery.fn.(anonymous function)jquery-1.7.1.js:6162
(anonymous function)temp.html:18
jQuery.Callbacks.firejquery-1.7.1.js:1049
jQuery.Callbacks.self.fireWithjquery-1.7.1.js:1167
jQuery.extend.readyjquery-1.7.1.js:435
DOMContentLoaded
答案 0 :(得分:2)
请参阅此回答https://stackoverflow.com/a/3603496/220299
它实际上可能正常工作,但脚本标签不可见。
答案 1 :(得分:0)
试试这个。
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
$(this).contents().find("head").append('<scr' + 'ipt type="text/javascript" src="//cross-domain.com/script.js"></scr' + 'ipt>');
}).appendTo("#content");
});