How to dynamically load and use/call a JavaScript file?
javascript
Solution
You could do it like this:
function loadjs(file) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = file;
script.onload = function(){
alert("Script is ready!");
console.log(test.defult_id);
};
document.body.appendChild(script);
}
For more information read this article : https://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/
Problem
I need to dynamically load a JavaScript file and then access its content. File `test.js` ``` test = function () { var pub = {} pub.defult_id = 1; return pub; }() ``` In this case it works: ``` <!DOCTYPE html> <html> <head> <script type="text/javascript" src="/test.js"></script> </head> <body> <script type="text/javascript"> console.log(test.defult_id); </script> </body> </html> ``` But I need to load it dynamically, and that way it does not work: ``` <!DOCTYPE html> <html> <head> </head> <body> <script type="text/javascript"> function loadjs(file) { var script = document.createElement("script"); script.type = "application/javascript"; script.src = file; document.body.appendChild(script); } loadjs('test.js'); console.log(test.defult_id); </script> </body> </html> ``` Error: `Uncaught ReferenceError: test is not defined(…)`