5 ms·
Why store state in DOM? Isn't that bad practice? I remember reading DOM access is the slowest part of JS [needs verification]. So you want to trade performance
by dreen 13y ago
Why store state in DOM? Isn't that bad practice?
I remember reading DOM access is the slowest part of JS [needs verification]. So you want to trade performance for few dozen kilobytes of assets that can be cached?
- lewispollard 13y agoBecause then you can create a fallback if Javascript isn't enabled - use a server side language to manipulate the DOM on page load to give the same state as if the Javascript were there
- bad_user 13y agoI'm not exactly sure what you're talking about, however mobile phones have awful bandwidth and awful browsers with not enough memory to cache everything they can. In the context of websites, you also want the experience of new users to be the best it can be. Basically, caching is nice, but it only works efficiently for applications that users visit often and that don't rely on links going viral, such as GMail. However, if you rely on caching for providing an acceptable user experience in cases where you rely on links going viral (such as Twitter), then you're screwed. Twitter has a mobile optimized web page that's much, much lighter than their desktop version and they did it for a good reason ;-)
- dreen 13y agoLet me rephrase then; storing state in DOM may be ok for small pages with some insignificant JS on top to provide progressive enhancement, but from web app point of view its totally unfeasible and saving a few KB is IMHO not worth it.
- bzbarsky 13y agoDOM access is the slowest part of JS in the same way that Window API access is the slowest part of a C++ app on Windows. "DOM access" covers everything from "WebGL calls" to "stroke a path in canvas" to "hey, redo the layout of the whole page" to "hey, store this string in a database" to "add an attribute to this element", depending on who you're talking to. Some of these are slow (redoing the layout of the whole page). Some are not too bad (e.g. in a current Firefox on Mac typical WebGl calls are about 2x slower than a corresponding GL call from a C program last I measured). Now obviously storing data in a DOM attribute is slower than storing it in a JS property, because there is more overhead: DOM attributes can dispatch mutation notifications, can affect styling, etc. If you don't need any of those things, you might be paying some cost that you don't need to pay. This typically starts to matter once you're doing a _lot_ of attribute sets, though. A typical attribute set in a modern browser is in the <100ns range on modern laptop hardware.