无需getElementById获取Canvas元素:代码压缩层面是否存在弊端?
document.getElementById("myCanvas") safe for canvas access (from a code compression perspective)? Great question—let’s dive into why this quirk works, the risks of skipping the explicit lookup, and whether the tiny byte savings are actually worth it.
Why does this even work?
Browsers have a long-standing legacy quirk: they automatically expose DOM elements with an id attribute as properties on the global window object. So when your canvas has id="myCanvas", you can reference it directly as myCanvas without fetching it first. That’s why your test code might work in Chrome, IE, and Firefox right now.
The drawbacks far outweigh the tiny byte savings
Even though omitting that line saves a few characters, here’s why it’s a bad tradeoff:
- Global namespace collisions: If any other script (or even a browser API) declares a global variable named
myCanvas, your code breaks instantly. For example, a third-party script definingvar myCanvas = "some text";would makemyCanvas.getContext()throw an error—you can’t call a method on a string! - Strict mode incompatibility: If you use
"use strict";(a best practice for safer, cleaner code), accessing an undeclared variable likemyCanvaswill throw aReferenceError. Strict mode doesn’t allow implicit references to these auto-exposed elements. - Poor readability & maintainability: Most developers expect variables to be declared or explicitly fetched. Skipping the lookup makes your code confusing—future you or a teammate might waste time wondering where
myCanvascame from. - No long-term guarantee: This behavior is a legacy quirk, not a core web standard. While browsers support it now, there’s no promise they’ll keep doing so forever. Deprecation could break your code down the line.
Code compression doesn’t need this shortcut
Modern minifiers (like Terser or UglifyJS) are smart enough to shrink your code without relying on risky quirks. For example, the explicit code:
var myCanvas = document.getElementById("myCanvas"); var canvasContext = myCanvas.getContext("2d"); canvasContext.fillRect(100, 100, 100, 100);
Will get minified to something like:
var a=document.getElementById("myCanvas"),b=a.getContext("2d");b.fillRect(100,100,100,100);
The difference in file size is negligible—just a handful of bytes—compared to the version without the lookup. And you get all the reliability of explicit code.
The safe, recommended approach
Stick to the explicit element lookup. It’s only one extra line, eliminates all the risks above, and minifiers will take care of shrinking it for you. If you really want to save a few more characters, you can even inline the lookup:
var canvasContext = document.getElementById("myCanvas").getContext("2d"); canvasContext.fillRect(100, 100, 100, 100);
This is still explicit, avoids the global quirk, and is just as minifiable.
内容的提问来源于stack exchange,提问作者redcanelation

