1

i have the folowing code:

window.document.getElementById("bufferTopic").innerHTML = "<img src='einstein/einstein.png' width='800' height='600'><script type='text/javascript' language='javascript'>alert('test');</script>"

i have it within a script file. the idea is to cache some images inside a div and when it completes run a script.

but it is not working.

any comments on why it is not working?

thanks.

EDIT: the script loads the image alright though.

iTEgg
  • 8,212
  • 20
  • 73
  • 107

3 Answers3

0

You are injecting javascript into the page, after it has loaded.

It will not execute just because it is now on the page.

You can read about the javascript execution model here.

Not sure why you can't simply write out your javascript after inserting the image:

window.document.getElementById("bufferTopic").innerHTML = "<img src='einstein/einstein.png' width='800' height='600'>";
alert('test');
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • but the image is not chaced yet. the innerHTML defines it. – iTEgg Dec 04 '10 at 13:47
  • @iEisenhower - Nothing to do with that. Javascript runs in the page in sequence. All scripts would loaded first, then be run. Any newly injected javascript would not be picked up. – Oded Dec 04 '10 at 13:49
  • yes my script is loaded/cached when the web page is accessed. sorry bit new at this. – iTEgg Dec 04 '10 at 13:54
  • @iEisenhower - Why do you think caching has anything to do with this. By the way - see my updated answer. – Oded Dec 04 '10 at 13:59
0

The issue you are having is related to how you injecting the javascript. Here is a good run down of how you should do this:

http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html

Hope this helps.

Bob

rcravens
  • 8,320
  • 2
  • 33
  • 26
  • The article you linked to describes how to add linked JS files, not how to inject JS _code_ to be executed immediately. – Oded Dec 04 '10 at 13:56
0

Make sure your script appears in the html after your bufferTopic element. Or, execute it in window.onLoad.

Also, an easier way to preload images is with pure javascript:

var image = new Image();
image.src = 'einstein/einstein.png';
Community
  • 1
  • 1
Emmett
  • 14,035
  • 12
  • 56
  • 81