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,

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use the onload event:

x.onload = function() { window.loadData(); }

Comments

Your Answer

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.