1

The code preloads an image into an image object and then (supposed to) set it to the image element src on HTML:

<!DOCTYPE html>
<html>
  <head>
    <script language="javascript">
        window.onload = function () {
            var oImage = new Image();
            oImage.onload = function () {
                document.getElementById('myImage').src = oImage;
                alert('done');
            };
            oImage.src = 'image1.jpg';
        }
    </script>
  </head>
  <body>
    <img id="myImage" src="" />
  </body>
</html>

Why it doesn't work?

2
  • Where is your 'image1.jpg' located? Is it in the same folder as your HTML file? Commented Jan 6, 2014 at 16:27
  • yes. I'm testing it locally. Commented Jan 6, 2014 at 16:29

1 Answer 1

6

Try

<!DOCTYPE html>
<html>

<head>

    <script language="javascript">
        window.onload = function () {

            var oImage = new Image();

            oImage.onload = function () {
                document.getElementById('myImage').src = oImage.src;
                alert('done');

            };

            oImage.src = 'image1.jpg';
        };
    </script>

</head>

<body>
    <img id="myImage" src="" />
</body>

</html>

You can't set a src to an image, you have to set it to the image's src. (PS: Added semicolon at the end and changed .src = oImage to .src = oImage.src)

DEMO

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

7 Comments

Yes, this is the solution. I've just discovered this in my fiddle: jsfiddle.net/Y2nPc/2
Well, it works. But using the .src won't it be loading the image again? I mean, isn't it the same as document.getElementById('myImage').src='image1.jpg'? The purpose is to load a bunch of images in advance. (prelodaing)
Browsers usually save all loaded images locally after loading them once to prevent reloading images every time you load a page within a website. And preloading an image using JavaScript just adds the image to that local directory. Your browser should do the rest. Also during the session your JavaScript image is loaded in the browser cache.
Lol, my fiddle was wrong; it was wrapped in a window.onload. Use this: jsfiddle.net/xPHyb/1
@MarvinBrouwer , in my case for example... all browsers here are set to store 0 cache on disk. But I think the browser will have it preloaded it in RAM anyway...
|

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.