Anders Tornblad, web developer

I'm all about the web

Monthly archive for March 2006

IMG problems in Firefox

While having some time to spare, I wanted to put some common JavaScript functions together in a library, but everything didn't work out the way I had hoped. At work everything went fine in all web browsers I had access to – IE 5.5, IE 6, IE 7, Firefox 1.5, Netscape 8.1 and Opera 8.5 – but when testing at home, nothing worked in Firefox. Nothing I did seemed to help.

The problem was image preloading – a common and simple method that I had used several times before:

var myimg = new Image(); myimg.src = "image-filename";

To solve the problem, I tried lots of different approches...

The first step – creating the Image object – was varied these ways:

var myimg = document.createElement("img"); var myimg = new Image(width, height); var myimg = new Image();

The second step – setting the src attribute value – was done like this:

myimg.src = "image-filename"; myimg.setAttribute("src", "image-filename"); myimg.attributes["src"] = "image-filename"; myimg.getAttributeNode("src").value = "image-filename"; myimg["src"] = "image-filename"; /* and finally: */ var srcAttr = document.createAttribute("src"); srcAttr.value = "image-filename"; myimg.setAttributeNode(srcAttr);

...but nothing worked. All different options worked perfectly in Internet Explorer and in Opera (a couple of variants didn't work in IE 5.5), but in Firefox nothing happened – no image was loaded, no matter what I did!

Finally I used the big guns:

var outer = document.createElement("div"); outer.innerHTML = ""; var myimg = outer.childNodes[0];

This solution actually worked! But since it has a really bad code smell, I didn't want to use it. It reminded too much about eval().

I Googled like a mad-man and found similar questions on several different forums and discussion groups from people in the same situation as I, but no answers. Finally I searched for preload images firefox problems, and just happened to stumble upon the Firefox development teams's configuration documentation. For some reason, my browser's value of the dom.disable_image_src_set setting was true – probably made that way by a security plugin that I had installed previously.

The dom.disable_image_src_set setting prevents JavaScript code from setting the value of the src attribute of img elements. When changing the setting from true to false (by first typing about:config in the Firefox address box), preloading images started working without a glitch in Firefox.