Bugfixed Clustrmaps tutorial: onload handlers

How embarrassing; my recent Clustrmaps tutorial was buggy. Not only was it buggy, but to the extent of terminating page load under Internet Explorer, at the spot where the code was inserted in the page, with a nasty error popup and possibly even without leaving the page there for the visitor to see even what had been loaded.

What the code did? It tried injecting nodes into the document with document.body.appendChild() before the entire document was loaded. Don't do this at home. (And I should have known better. I even pasted that code into the template of Some Assembly Required, apparently without even testing it in IE first.)

On the other hand, this gives me good opportunity to hand down a tip on a technique I use to use when writing tutorialesque code snippets to avoid having to explain how to add code to the <body onload> event handler, catering for cases such as there already being one, and so on. In my code, I was to add a clustrmaps() call to it, and this is how I wrote that code, in the end:

var then = window.onload || function(){};
window.onload = function(){ clustrmaps(); then(); };

This first picks up any former onload handler, and adds a new one that first runs the code you supply, then the one that might have been there in the first place. If you want to make extra sure that the addition of your own code does not break the formerly in place onload handler by some exception aborting your code, run the then() method before calling your own additions.
blog comments powered by Disqus