Javascriptlookouts

20060221138

As with anything that depends on a web browser for rendering, javascript falls victim to different interpretations from different browser vendors. Here are two I’ve had to deal with recently.

Extra whitespace

Mozilla includes a text node between all elements on a page. Internet Explorer does not. This means given a page with the structure

<body>
<h1>Extra Nodes</h1>
</body>

a reference to document.getElementsByTagName("body")[0].childNodes[0] refers to different elements in each browser. Mozilla references an empty text node while Internet Explorer references the h1 (childNodes[1] to Mozilla). Not only does the additional text node cause a Mozilla browser to have a larger DOM tree, but references to each node within the childNodes array are different.

Mozilla offers a solution to a make its structure work the same as IE. There are other methods out there too. However, my preference has been to avoid using methods that can get confused by this discrepancy altogether and instead use methods such as getElementsByTagName or getElementById as it seems to lead to cleaner and more readable code anyway.

Image.onload event

The image.onload event should occur when an image is finished loading. And it does. Except in IE when that image is already cached. Firefox though recognizes the event whether the image is cached or not. In a way I can understand IE’s interpretation however recognizing the event regardless of where the image is loaded from makes more sense. When cached, the event never happens in IE.

One way to avoid this is to keep the image from loading from the cache by tagging a random value onto its name. Not only do some browsers not get along well with this method, it of course defeats the purpose of the cache in the first place. Instead, I use the following code:

var loadimage = new Image();
loadimage.src = source;
if (loadimage.onload) {
loadimage.onload = //do something
} else {
//do something
}

With loadimage being the image to get the onload listener assigned to it, if the listener is recognized, it is assigned and the code will execute once loaded. If it isn’t recognized, the code is executed immediately. In Firefox, the listener is always assigned whether the image is cached or not. In IE, when not cached, the listener is assigned and works as expected. If the image is cached, the code is executed immediately, sans listener. Either way, the event only occurs after the image is available.

These are both relatively minor issues and can probably be avoided all together in most cases.


Skateboards and bikes are better at nights

Skateboards and bikes are better at nights. 0 comments.


Search WayTooCrowded
The Header Should Always Point Home