是否可以在动态构建的iframe页面上使用require.js?
问题描述:
因此,我正在使用jQuery元素动态构建的页面中的iframe。我想在该iFrame内以特定顺序加载几个外部JavaScript文件。是否可以在该iFrame中加载require.js,然后使用它通过js代码加载外部js文件?是否可以在动态构建的iframe页面上使用require.js?
答
我做了一些测试,终于得到了它的工作是这样的:
选择的iframe头
$iframe = $('#target'),
$head = $iframe.contents().find("head");
添加需要设置为iFrame
$head.append($("<script>", {src: "/path_to/require.js"}));
出于某种原因data-main
属性正被如此漠视我不得不自己打开配置
var startRequire = (function() {/**
requirejs.config({
"baseUrl": "/your/path",
//more config
});
// Load the main app module to start the app
requirejs(["/your/path/main.js"]);
**/})
.toString().split('\n').slice(1, -1).join('\n'); //this hack is here just so I don't keep adding plusses and "'", configs can get complex
$head.append($('<script>').html(startRequire))
请记住,从父项添加.js到iframe时,加载脚本的当前范围仍然是父项,所以如果您在main.js
中使用jQuery,则必须声明范围:
var iframe = $('#target')[0].contentWindow.document; //iframe
$('.selected', iframe); //look for element with class selected within the iframe
您*尝试*它? – Louis 2014-10-21 23:20:49
您是否找到解决方案?我现在正在处理类似的问题。 append($(“