0

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() ?

3
  • 1
    E.g., calltest() could be the last statement in the JS file you inject. Commented Jan 22, 2013 at 17:06
  • 2
    Check this post stackoverflow.com/questions/1293367/… Commented Jan 22, 2013 at 17:10
  • Yeap both these techniques solved my issue... I opted for Marcell just because its a bit simpler. Thanks! Commented Jan 22, 2013 at 17:16

2 Answers 2

1

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

Comments

0

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

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

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.