HTML and CSS Reference
In-Depth Information
9.3 Do Not Make Assumptions
“Do not make assumptions” is perhaps the most important rule of unobtrusive
JavaScript. It sums up most aspects of clean JavaScript in a single phrasing. In
this section we will go over the most common assumptions and why they make it
challenging to write robust scripts for the web.
9.3.1 Don't Assume You Are Alone
Never assume that scripts run in isolation. This applies to application developers
as much as library authors, because most websites today use code from at least one
external source.
Assuming scripts run in isolation makes running them alongside scripts we don't
control harder. For the last few years, all the sites I've worked on use at least one
external analytics script and most of these scripts use document.write as a last
resort. document.write has a nasty side-effect of wiping the entire document
if used after the DOM has fully loaded. This means that asynchronously loading
content invoking the offending code will cause the site's analytics script to effectively
break it completely. I've seen maintenance developers break down in tears as they
realize what is causing their site to fail, and it ain't a pretty sight. How to Avoid
The less we contribute to the global environment, the less we will depend on it.
Keeping our global footprint small reduces chances of conflicts with other scripts.
Techniques to minimize global impact were described in Chapter 6, Applied Func-
tions and Closures. Besides keeping the number of global objects low, we need to
watch out for other forms of global state, such as assigning to window.onload
or using the aforementioned document.write .
9.3.2 Don't Assume Markup Is Correct
When separating concerns, we should strive to keep as much markup in the doc-
ument as possible. In practice this equates to using the “fallback” solution as a
basis for the scripted solution as much as possible. However, this also means that
scripts are no longer in complete control of markup, so we need to be careful. The
original markup may be compromised in many ways; it may be compromised by
other scripts, by document authors, or by invalid markup that results in a different
document structure when parsed.
Search WWH ::

Custom Search