omri
omri

Reputation: 615

Chrome - Image not loaded when loading from JS

I am trying to simply load an image on page load.

When i use a simple src it works ok:

<img src="url.png" />

But when I try to load it from my JS It does not load:

<img id="loadImage" src="" />

JS:

var _img = document.getElementById('loadImage');
_img.src = 'url.png';

The url is shown as 'not found'.

I am getting the same error as in this post : What does status=canceled for a resource mean in Chrome Developer Tools?

I cant seem to solve it, Why is that happening.

Upvotes: 0

Views: 238

Answers (2)

Frondor
Frondor

Reputation: 3466

Why don't you try and save the whole image tag in a variable? This you you are not providing invalid HTML markup like empty src.

Just change your HTML to

<div id="imageholder"></div>

and use this code

$(document).ready(function() {
    var image_1 = $('<img src="img/url.png" />');
    $("#imageholder").append(image_1);
});

Take this fiddle and try :)

http://jsfiddle.net/aBF67/

NOTE: I'm using jQuery for that example :)

Upvotes: 1

Andrea Falzetti
Andrea Falzetti

Reputation: 360

Try yo create a new Image object and assign it to the src attribute. Example:

var imgObj = new Image();
imgObj.src = "http://.....jpg";

var _img = document.getElementById('loadImage');
_img.src = imgObj;

I hope it helps.

Upvotes: 0

Related Questions