Frage

I am trying to load a simple image using javascript, for that I am using following code

function loadImage(src) {
    var image = new Image;
    image.onload = function() {
        document.body.appendChild(image);
    };
    image.onerror = function() {
        document.body.appendChild(document.createTextNode('\nError loading as image: ' + this.src));
    };
    image.src = src;
}

loadImage('http://www.linkedin.com/favicon.ico');
loadImage('http://www.facebook.com/favicon.ico');

Fiddle Link

The problem I am facing is whole thing working in chrome and firefox but not working in internet explorer. I am not much used to with javascript.

Any solutions ?

War es hilfreich?

Lösung

IE will not load an ICO image into the browser unless its contentType is image/x-icon.

I can confirm by looking at the network tab in Firefox that the contentType for the LinkedIn image is application/octet-stream which would explain why IE will not show it while the Facebook image has a content type of image/x-icon which IE likes.

There is nothing you can from the browser other than don't request an image that has that type set on its server. I'm quite sure that sites like LinkedIn will have other small images from there site that you can link to.

FYI, if you look at the linkedIn source for it's homepage, you will find a tag that points to http://s.c.lnkd.licdn.com/scds/common/u/images/logos/favicons/v1/16x16/favicon.ico which works just fine in IE (because it's an image/x-icon).

Andere Tipps

It is also worth noting that some older versions of IE (and to be honest, I don't recall if IE8 is one of the affected ones), the onload event is NOT fired of the image is loaded from cache.

function loadImage(src) {
    function doOnLoad() {
        document.body.appendChild(image);  
    }

    var image = new Image;
    image.onload = doOnLoad;
    image.onerror = function() {
        document.body.appendChild(document.createTextNode('\nError loading as image: ' + this.src));
    };
    image.src = src;
    if (image.complete) {
      doOnLoad();
    }
}
call the function on window load :-
<script  type="text/javascript">

function loadImage(src) {
var image = new Image;
image.onload = function() {
    document.body.appendChild(image);
};
image.onerror = function() {
    document.body.appendChild(document.createTextNode('\nError loading as image: '  +     this.src));
};
image.src = src;
}

window.onload=loadImage('http://www.linkedin.com/favicon.ico');

</script>

 the image is not loading, when you call the method after load all the elements then it will work.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top