ToOsIK
ToOsIK

Reputation: 643

Call JavaScript function after referencing a new JS file added via JavaScript call

ok the title might be abit vague, but the idea is quiet simple.

I have a bit of JavaScript code that adds a reference to a JS file in the Head section of an HTML page, after the new JS file has been added, I would like to call a function that exists within this newly added JS file. So I have a link (with javascript:eval) that executes the following JS code:

//PART 1
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script'); 
script.setAttribute('type', 'text/javascript'); 
script.setAttribute('src', 'http://localhost/test.js'); 
head.appendChild(script); 

//wait for JS file to load should go here

//PART 2
calltest(); //calltest is a function that exists within http://localhost/test.js

This works fine if there is a delay between PART 1 and PART 2 (for example, they are on 2 separate links that the user clicks on sequentially), but doesn't work if the whole code is executed sequentially on one link (am guessing because the JS file (added in PART 1) hadn't had the chance to load yet). Is there anyway to make PART 2 wait on PART 1 to fully complete?, perhaps some sort of delay or wait on the JS file to be retrieved before calling the function calltest() ?

Upvotes: 0

Views: 194

Answers (2)

ToOsIK
ToOsIK

Reputation: 643

As per Marcell's comment, I endedup adopting the following solution:

calltest() could be the last statement in the JS file you inject

Upvotes: 0

Jon Greene
Jon Greene

Reputation: 25

This should do it.

window.onload = calltest;

Or perhaps add this to your first script

script.onreadystatechange= function () {
  if (this.readyState == 'complete') calltest();
 }
 script.onload= calltest;

Upvotes: 1

Related Questions