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?
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?
Share Improve this question edited Jan 6, 2014 at 16:34 Sachin Jain 21.9k34 gold badges110 silver badges176 bronze badges asked Jan 6, 2014 at 16:23 AzevedoAzevedo 2,1897 gold badges35 silver badges53 bronze badges 2- Where is your 'image1.jpg' located? Is it in the same folder as your HTML file? – Marvin Brouwer Commented Jan 6, 2014 at 16:27
- yes. I'm testing it locally. – Azevedo Commented Jan 6, 2014 at 16:29
1 Answer
Reset to default 6Try
<!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