I have a local JS file that needs to be called using a script object. However, I am not able to get the functions to run. Here's the code snippet.
<script type="text/javascript">
var x = document.createElement("SCRIPT");
x.type = "text/javascript";
x.src = "file:///C:/scripts/localscript.js";
//one of the functions is loadData();
loadData(); //I'm getting reference error, loadData is not defined.
</script>
Thank you,
asked May 23, 2018 at 9:44
Jaime Dolor jr.
9292 gold badges13 silver badges31 bronze badges
2 Answers 2
You need to create a script element and insert it in DOM (mostly under head) to load the script. When that script is loaded by the browser, whatever you return from that script will be available.
Consider sampleScript.js with below code
(function(window){
'use strict';
window.app = {
sayHi: function() {
console.log('Hey there !');
}
};
})(this);
To load this script, I do
<script>
var node = document.createElement('script');
node.src = 'sampleScript.js';
node.addEventListener('load', onScriptLoad, false);
node.async = true;
document.head.appendChild(node);
function onScriptLoad(evt) {
console.log('Script loaded.');
console.log('app.sayHi ---> ');
app && app.sayHi();
}
</script>
Taking cues, you can fit to your need. Hope this helps.
answered May 23, 2018 at 10:16
Ravi Tiwari
9729 silver badges18 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use the onload event:
x.onload = function() { window.loadData(); }
answered May 23, 2018 at 9:46
David Hellsing
109k44 gold badges181 silver badges214 bronze badges
Comments
lang-js