0

I have two js files as shown below

example.js

  var imported = document.createElement('script');
    imported.src = 'myfile.js';
    document.head.appendChild(imported);
  myFunction();

myfile.js

 function myFunction() {
      alert("hello");
 }

When I try to run the example.js I get the error that myFunction() is not defined. Can you please tell me the reason. Thanks in advance

naveen
  • 53,448
  • 46
  • 161
  • 251
  • is myFile.js referenced before example.js? – kemiller2002 Aug 25 '16 at 19:44
  • hey try to wait till script loaded and maybe use a full url to the script: have a look in here: [stackoverflow :)](http://stackoverflow.com/questions/3248384/document-createelementscript-synchronously) – Eldo.Ob Aug 25 '16 at 19:47
  • The script is loaded asynchronously so when you call `myFunction()` it might not even been downloaded yet. – Matias Cicero Aug 25 '16 at 20:00

1 Answers1

1

Adding script to DOM not means that script is loaded, the same thing is with any resource, adding image to DOM does not means image is loaded. Loading scripts or images or any url content is asynchronous, DOM not waits for complete of load. Your code is calling function immediately after adding script to page structure, so script is not loaded yet.

Pure Js solution:

Dynamically load external javascript file, and wait for it to load - without using JQuery

Jquery solution

In Jquery exists helpful method getScript:

$.getScript( "myfile.js", function( data, textStatus, jqxhr ) {
  //here script is loaded and functions can be called 
});

Last thing to know is that appendChild add child as last child. So taking Your example:

<head>
<!-- other head elements -->
<script src="example.js"></script>
<!-- other head elements -->

<!-- HERE WILL BE ADDED FILE, AS LAST CHILD -->
<script src="myFile.js"></script>
</head>

So myFile.js will be added as last in head and for sure will be not available in scripts added before it.

Community
  • 1
  • 1
Maciej Sikora
  • 19,374
  • 4
  • 49
  • 50