所以我正在使用jQuery元素动态构建的页面中的iframe。我想在iFrame中以特定顺序加载几个外部javascript文件。是否可以在该iFrame中加载require.js然后使用它通过js代码加载外部js文件?
答案 0 :(得分:0)
我做了一些测试,最后让它像这样工作:
选择iframe头
$iframe = $('#target'),
$head = $iframe.contents().find("head");
将if require添加到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