0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

Use the onload event:

x.onload = function() { window.loadData(); }
answered May 23, 2018 at 9:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.