0

how can i t change this code to run the function when the js library finish loading? uisng vanilla javascript

because i'm using a timer that didn't worked for slow internet connection

imported = document.createElement('script');
imported.src = 'https://pastebin.com/raw/dRap1YD8';
document.head.appendChild(imported);

    var delayInMilliseconds = 1000; 

setTimeout(function() {
.
.
.
}, delayInMilliseconds);

Note that pastebin is just for test

user11845248
  • 131
  • 8
  • 1
    This has been asked before, you would want to look at Promises. https://stackoverflow.com/questions/34638221/load-jquery-with-javascript-using-promises – Snowmonkey Jul 31 '19 at 20:24

2 Answers2

3

What you are looking for is the onLoad method. Take a look here at the api, It's gonna look like

imported.onload = function() { alert('loaded'); }

Mauricio Sipmann
  • 465
  • 6
  • 21
1

Do like:

var imported = document.createElement('script');
imported.onload = function(){
  /* it's loaded - do stuff here */;
}
imported.src = 'https://pastebin.com/raw/dRap1YD8';
document.head.appendChild(imported);

Make sure you put your load Event before you assign the .src, otherwise it may never fire.

StackSlave
  • 10,613
  • 2
  • 18
  • 35