If this is the first time you’re hearing about it, brace yourself! We can see it in action simply by adding an ID to an element in HTML:
Normally, we’d define a new variable using
getElementById("cool") to select that element:
But we actually already have access to
#cool without that rigamorale:
id — or
window[ELEMENT_ID]. Again, this isn’t exactly “new” but it’s really uncommon to see.
As you may guess, accessing the global scope with named references isn’t the greatest idea. Some folks have come to call this the “global scope polluter.” We’ll get into why that is, but first…
One thing that might not be well known is that browsers had to put in place a few precautionary measures — with varying degrees of success — to ensure generated globals don’t break the webpage. One such measure is…
And the opposite is true as well:
This behavior is essential because it nullifies dangerous overrides such as
<div id="alert" />, which would otherwise create a conflict by invalidating the
alert API. This safeguarding technique may very well be the why you — if you’re like me — are learning about this for the first time.
Let’s say we chuck the criticisms against using named globals and use them anyway. It’s all good. But there are some things you might want to consider as you do.
This code works perfectly fine in Chrome, but throws the following error in Safari.:
Safari lacks support for the
CookieStore API as of this writing. As a result, the polyfill is not applied because the
img element ID creates a global variable that clashes with the
That script grabs a reference to the input element and invokes
focus() on it. It works correctly. Still, we don’t know how long it will continue to work.
Let’s sum up how we got here:
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the web platform, for example. Instead of this, use
I think the fact that the HTML spec itself recommends to staying away from this feature speaks for itself.
If you need help creating a digital marketing strategy for your business, don’t hesitate to contact one of Digidude’s consultants.