I just don't get it.
How can so many smart people be so collectively bad at something as simple as Javascript on a web page?
It's just not that hard. And yet, not an hour goes by when I'm not stopped in my tracks by at least one javascript error. And it's especially sad because many of these errors are coming from well known sites, with huge development budgets and plenty of good talent that really should know better. Observe:
That was just a ten minute sample of browsing today.
The One Rule of DHTML Programming
Look, it's not that hard to do this stuff right. In fact, here is everything you'll ever need to know about Dynamic HTML Programming with Javascript:
Test EVERYTHING before you reference it.
That's it. Simple. Every little scrap of code you write needs to live inside its own little IF block that tests to make sure that the things it's expecting to interact with really exist. Here's how:
BAD:
gbN2Loaded.style.display='none';
|
Good:
if (window.gbN2Loaded)
{
gbN2Loaded.style.display='none';
}
|
BAD:
document.getElementById('myDiv').innerHTML
= 'stuff';
|
Good:
if (document.getElementById('myDiv'))
{
document.getElementById('myDiv').innerHTML
= 'stuff';
}
|
I don't care that
Google's API Reference told you to put
<body onunload='GUnload()'>
into all your pages. That's just example code, and it's
not intended to be used in the real world.
Real World Javascript will need to survive in dozens of strange browser environments that do things in strange unexpected ways, and as soon as you get it working right, Junior Dev Jimmy will accidently include it on every single page on your site and suddenly it won't be able to find the things it needs to live. When that happens, it needs to quietly stop trying to do stuff instead of throwing error messages all over the place.
What you need to do about it
Ok, cool, you've fixed everything, but you're not done yet. There's one more thing you need to do right this second. You need to turn on those annoying Script Error popups in both Internet Explorer and Firefox, and you need to keep them on from here on out. Don't just do it for your own machine, but for every computer owned by every employee of your company.
Yes, I know that you turned them off on purpose because they make the internet basically unsurfable, but most casual users of your site will have them on by default. That means that most casual users will see every single little script error that your site throws at them, and they won't like it. Those errors are pissing off real people right this minute, and you need to know about it. If you arrange it so that they start pissing off you and your co-workers too, you just might find the incentive to get rid of them once and for all.
by
Jason Kester
Discuss on hacker news