I know its bad to store data in the DOM, but why?

后端 未结 4 1691
一向
一向 2020-12-07 18:47

I\'ve heard over and over again that it is bad practice to \"use the DOM as a database.\"

While I mostly agree with that sentiment, this question is more about the l

4条回答
  •  离开以前
    2020-12-07 19:42

    There are some fundamental arguments against using the DOM to store data:

    1. The DOM is supposed to be a view of data. The properties of DOM elements should be metadata for the elements themselves, not data from the model.

    2. You should not add random properties to host objects as you have no idea what they might do with them.

    3. You have the same issue as global variables - if it becomes common practice, you will have to adopt a scheme to avoid name collisions.

    There is also the argument that the DOM is a pretty ordinary data store and that object structure with indexes will be much more efficient for anything other than trivial data needs.

    If you only have small amounts of data and have full control over your pages, then go ahead and put data in data- attributes and properties. But do not store large chunks or complex structures.

    Oh, and I don't think there are any performance issues - accessing an element and its properties in the DOM is likely no faster or slower than accessing some part of an object structure, though I'm sure there are faster and slower ways of doing both.

提交回复
热议问题