I suggest opening F12 debug mode and pasting into the console to see the output of the code snippets (the blog includes jQuery, so you can use $ directly).
Simple Data Caching
jQuery gives us the power to manipulate the DOM tree, which of course also means we can use the DOM tree for simple data storage — temporarily saving variables, or saving them as JSON strings.
The basic working method is like the code below:
1 | // save |
This is the most basic operation, and also one that won’t go wrong.
The Second Way
Some of you saw <div data-info="12345"></div> — that’s really just setting an attribute on a div.
So why not do this: tmpDiv.attr('data-info', '123')?
Look at the code below:
1 | var tmpDiv = $('<div />'); |
At this point, if you honestly go back to the first way and don’t modify attr directly, you’ll have no problems in the future.
But if you want to explore deeper, keep reading.
Why Does the Inconsistency Occur?
See the documentation here: data-html5. The docs contain this sentence:
Since jQuery 1.4.3, data-* attributes are used to initialize jQuery data. An element’s data-* attributes are retrieved the first time the data() method is invoked upon it, and then are no longer accessed or mutated (all values are stored internally by jQuery).
The data-* attribute can be used to initialize jQuery’s data function; on the first call of data(), the data is
stored inside jQuery and no longer accessed.
If you’re quick on the uptake, reading the docs is enough — at least you know that after jQuery has used data-*,
it no longer depends on its value and keeps an internal copy.
Or Maybe You Want to Read the Source Code
I hadn’t read jQuery source before and hadn’t used it much; this time I hit a problem — never expected to fall into it. In a fit of pique I read the source, and share it here. The code related to the data function is in src/data.js and src/data/Data.js.
There are a few key pieces of code.
1 | Data.prototype = { |
By now I think you understand: if the cache has a value, data-* will not be re-read.
Moreover, jQuery‘s data() and the data-* attribute are two different things — related only at initialization.
Afterwards, the two can very well become inconsistent.
How Can They Be Consistent?
In the end, inconsistency really does exist between the two. There are three solutions:
Don’t use the
data-*scheme from the start: after all, jQuery itself provides the data() function — there’s simply no need to usedata-*to set attributes.Only use
data-*: the benefit is you can inspect the data directly via the DOM, and debugging is indeed fast.Keep them in sync manually: if you insist on using both together, you should reflect on why you’re courting death like this. It’s not impossible — besides the
datafunction,jQueryhas another function calledremoveData; if you don’t mind the trouble, call it once before each use.