Javascript 从<;访问requirejs模块;脚本>;标签
我目前有一个requirejs模块,它位于远程服务器上,例如下面定义了一些主干视图、模型Javascript 从<;访问requirejs模块;脚本>;标签,javascript,backbone.js,jupyter-notebook,requirejs,Javascript,Backbone.js,Jupyter Notebook,Requirejs,我目前有一个requirejs模块,它位于远程服务器上,例如下面定义了一些主干视图、模型 define(['...'], function() { ...... return { model : suggestion_model, view : suggestion_view }; }); 正在动态加载到另一个文件中的 let script = $("<script>").attr({ src: "http://localhost:9000/a
define(['...'], function() {
......
return {
model : suggestion_model,
view : suggestion_view
};
});
正在动态加载到另一个文件中的
let script = $("<script>").attr({
src: "http://localhost:9000/assets/javascripts/autocomplete/autocomplete-model-view.js",
});
console.log(script);
$("head:first").append(script);
let script=$(“”)。attr({
src:“http://localhost:9000/assets/javascripts/autocomplete/autocomplete-模型视图.js“,
});
console.log(脚本);
$(“head:first”).append(脚本);
当我转到标记时,我看到文件已加载,但我无法访问任何代码中要使用的模块
我如何才能真正访问其他文件中定义的这些requirejs模块 您可能无法通过将远程requirejs模块直接注入脚本标记来访问它们。您可以尝试以下步骤来访问它们 假设我们有一个名为
remotemodule
define(['remotemodule'], function() {
return {
model : function(){
return "Im a remote model";
},
view : function(){
return "Im a remote view";
}
};
});
要在浏览器中访问它
您需要首先将requirejs
脚本添加到html中
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js" type="text/javascript"></script>
然后可以调用require([“remotemodule”],函数回调)
来加载脚本。这里,一旦加载脚本,就会执行回调
require(["remotemodule"], function(loaded_script){
console.log(loaded_script);
document.getElementById("remotemodule").innerText = loaded_script.model();
})
下面是一个简单的演示
require.config({
路径:{
“远程模块”:https://raggedlostcone.nithinthampi.repl.co/"
}
});
require([“remotemodule”],函数(加载的_脚本){
console.log(加载的_脚本);
document.getElementById(“remotemodule”).innerText=loaded_script.model();
})
文件
加载。。。
您确定您的代码是在$(“head:first”)之后加载到浏览器上的。追加(脚本)代码>是否执行?尝试检查您的代码中是否存在define
或require
这似乎有效!我还有一个问题,在我的远程代码中,我使用了一些下划线模板,比如'template\u box=\u.template(autocomplete\u box)`,但它抱怨n.replace不是一个函数。这只是我如何使用模板的一个代码问题,还是缺少依赖项或其他什么具体地说,我的IDE中缺少AMD模块依赖项,但是,在控制台中抛出了一个未定义的类型错误。无论如何,还是要使请求模块同步。如果在远程模块中有多个AMD依赖项,则应该考虑将它们组合成单个包并在UI中使用。如果是非AMD模块,您可以使用shim config加载依赖项。请参阅下面的REPL,我在远程模块中使用下划线JS
require(["remotemodule"], function(loaded_script){
console.log(loaded_script);
document.getElementById("remotemodule").innerText = loaded_script.model();
})