I currently have a requirejs module that lives on a remote server such as the below that defines some backbone views, models
define(['...'], function() {
......
return {
model : suggestion_model,
view : suggestion_view
};
});
that is being dynamically loaded in another file as such
let script = $("<script>").attr({
src: "http://localhost:9000/assets/javascripts/autocomplete/autocomplete-model-view.js",
});
console.log(script);
$("head:first").append(script);
I see that the file is loaded, when I go to my tag but I can't access the module to be used in any of the code.
How could I go about actually accessing these defined requirejs module in some other files?
You might not be able to access remote requirejs modules by injecting them directly in a script tag. You can try the below steps to access them.
Assuming we have a remote module named remotemodule
define(['remotemodule'], function() {
return {
model : function(){
return "Im a remote model";
},
view : function(){
return "Im a remote view";
}
};
});
To access it in your browser..
You need to add requirejs
script into your html first.
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js" type="text/javascript"></script>
This should give you a global object require
. You can call the config
function on require
to define the remotemodule
by specifying the path
to the script.
require.config({
paths: {
"remotemodule": "https://raggedlostcone--five-nine.repl.co/"
}
});
And then you can call require(["remotemodule"], function callback)
to load the script. Here the callback is executed once the script is loaded.
require(["remotemodule"], function(loaded_script){
console.log(loaded_script);
document.getElementById("remotemodule").innerText = loaded_script.model();
})
A simple demo below.
require.config({ paths: { "remotemodule": "https://raggedlostcone--five-nine.repl.co/" } }); require(["remotemodule"], function(loaded_script){ console.log(loaded_script); document.getElementById("remotemodule").innerText = loaded_script.model(); })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://requirejs.org/docs/release/2.3.6/minified/require.js" type="text/javascript"></script> </head> <body> <h1 id="remotemodule"> loading... </h1> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.