0

I have an external javascript that contains something like:

document.writeln("<script type='text/javascript' src='...'></script>");

In the original html i have something link

<div id="banner">
    <script type="text/javscript" src="<the external javascript above>"></script> 
</div>

How can i load that delayed?

I've tried using window.setTimeout and append that javascript but its not working.

Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.

Thank you.

3
  • Try the answer to this question: stackoverflow.com/questions/610995/… Commented Feb 7, 2012 at 10:11
  • @bukko - i've tried that but no luck. The writeln its not executed in same div. Commented Feb 7, 2012 at 10:11
  • Strange - I posted as an answer but it comes up as a comment :/ Commented Feb 7, 2012 at 10:11

4 Answers 4

2

You can call your injection code on window.onload.

window.onload = function() {  
  inject();  
  doSomethingElse();  
}; 

window.onload will wait until all assets have finished downloading, such as images and scripts. After scripts are downloaded, you can inject your code to page.

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

1 Comment

I know how to execute after the page was loaded, i want to be executed correctly. The JavaScript its not executed in the right place.
0

Maybe a better way to do it would be to add a delay to the script.
Also, if you use something other than 'document.writeln' for example:

$('#banner').append(...);

you can better direct where it goes.

3 Comments

Read the question again and you will see i already tried that
Can you show the code you tried? I use those all the time and they work fine.
Also, what is the script doing? Does it really need to execute within the div? You can manipulate elements from anywhere within your document, and ideally scripts should stay in the header.
0

There is an open source javascript library for doing this kind of thing: http://labjs.com/

I have used it in the past and it worked very well.

Comments

0

Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.

That is not entirely true. Especially if the div is empty you could simply use: document.getElementById('banner').innerHTML = "<h1>HTML-Output here.</h1>"

Bukko's answer would work as well if you are using jQuery. My answer is pure Javascript. With this newfound freedom you should be able to simply put the loading of your script at the bottom of the page or use a custom body.onload() function Edit: or simply follow Samet's suggestions in conjunction with the .innerHTML. Hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.