因此,我正在使用一个使用jQuery元素动态构建的页面中的iframe。我想在iFrame中以特定的顺序加载几个外部javascript文件。是否可以在该iFrame中加载require.js,然后使用它通过js代码加载外部js文件?
发布于 2015-01-16 19:09:24
我做了一些测试,最终让它像这样工作:
选择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
https://stackoverflow.com/questions/26497988
复制相似问题