Search code examples
javascriptjqueryperformancesecurityjquery-data

Adding arbitary data in Jquery using .data()


I was trying add arbitrary data while doing this I got following doubts in my mind:

  1. How much data I can add, is there any limit?

  2. Does it affect in anyway to performance/execution Speed?

  3. And what about safety of data, is it safe?

  4. Where does these get stored?


Solution

  • Since you haven't provided any real or example markup with the attributes you've thought to use, let's just talk briefly about HTML5's data--prefixed attributes: What are they, why are they there, and what they're not. This should go a long way to clear up your anxiety.

    First, what are they? The W3C specification is clear:

    3.2.3.9 Embedding custom non-visible data with the data-* attributes

    ... an attribute in no namespace whose name starts with the string "data-" ... intended to store custom data ... for which there are no more appropriate attributes or elements.

    You might notice it's also emphatically stated what they are not meant to do. Before we get to that, and what mechanism is designed for their appropriate implementation, let's step back briefly and consider what was before data- came to be.


    If you're familiar with HTML, you know there are defined core (global) attributes (id, class, etc.) all elements inherit. There are attributes that float amongst groups for different reasons (src, accesskey?, etc.). There are specialized event attributes, some fairly specific or deprecated or otherwise oddball attributes.

    There are even microsyntaxes and microformats. Let's focus here, though; the former is about expressive attribute syntax (<input type="email" required ...), the latter is prohibitively not inclusive of data- attributes (due to rules of structured attribute specificity).

    You should get the idea somebody, at length, thought this stuff through. All the above has everything to do with the way this marked-up content is described purposefully (and if possible semantically) to the browser. It's not willy-nilly it exists as it does. Neither is it set in stone (HTML5 is now living), nor equivalent to that XML namespace-free hooliganism XHTML-doctype'd webpages purport to be.

    If you've never thumbed through one, go through the HTML5 spec. It's interesting, once you get the hang of reading it's stilted and wobbly unhuman diction.


    Making our way back, we're now gifted this oddball data-* syntax, plus a clumsily executed prose depicting some dataset and scripting beast that's going to make it all wonderful.

    And so you think (naturally) what is this for and what can I do with it? Good question.

    There's two answers, what you should do, and what you should avoid at all cost. The former will have you frolicking in a daisy-lined fragrant garden of awesomeness; the latter, Beelzebub himself may seek your very soul. (Or at least wonder what you're up to.)

    What you should do is use data- to address those situations where you need to associate data of some sort to an element or elements on the page. Not willy-nilly; don't be tempted by the barbeque flames of hell. When you need that data and you find yourself possibly resorting to something like:

    var = '<?=json_encode($restaurants)?>'; // This is so sad, really.
    

    Or, God help us:

    <a id="client-005" rel="200907,$5000;200908:$3500;oh,why" ...
    

    Get it? Sales data for the "client" in that element (we think... hope...). Asynchronously grabbing data has obviated some of the need for these eccentric approaches. Also, some clever folks figured out you could:

    <script type="text/x-data-csv">
    Client, Year, Sales
    Bill's Salon, 200904, $5300
    ...
    

    NIfty. For globs of data, a la massive d3.js stereoscopic data visualizations, this is definitely good enough. Also, it's not a great fit for data- attributes. But this could be:

    <select name="service_tech">
      <option data-name="Bobby Jones" 
              data-email="[email protected]" 
              data-phone="xxx.xxx.xxxx"
              data-title="Diesel Mechanic"
              data-days-available="MON-THU"
              data-shifts-available="2ND3RD"
              value="EMP00345">Bobby Jones</option>
    

    Or:

    <section id="quiz"
             class="quiz stage block"
             data-quiz-hard-end="2013-03-10 00:00:00"
             data-question-total="10"
             data-question-current="6"
             data-session-keep-alive="30 minutes">
      <article id="question"
               class="single view deadline warning"
               data-question-save-state="true"
               data-question-record-incorrect="false"
               data-question-incorrect="block with hint"
        <ol id="quiz-possibles"
            class="block multiples unanswered"
            data-answer-timeout="60 seconds"
            data-answer-time-expiry-action="replace in-place random fresh"
            data-answer-timer-display="top right #quez.frame"
            data-answer-hint-pop="elapse 30 seconds"
            data-answer-hint="The square of the hypotenuse is left of right to this.">
    

    That's awesome. Think about it how cumbersome that would be to embed an ad hoc block of related data like that without resorting to madness, depression or AJAX death by a thousand queries?

    Imagine that configuration coupled with Select2 and a custom $.change() search on those attributes. Now we're cooking with gas.

    What data- attributes are not is more abstract because by nature, it's all about poor implementation somehow. So consider:

    <body data-wednesday-salutation="Hello" ...
    
    <img data-class-name="dogs"
         data-filename="rover.png" 
         data-url="/some/path/rover.png"
         data-dog-bark="yes" ...
    
    <p data-groovy-font="blue dog demi mono" ...
    
    <em data-what-is="today" data-answer="Monday!" ...
    

    Does any of that make sense? There's more subtle ways for inanity or twiddly thinking to worm or barge it's way into data- misuse and misappropriation of course, but they all come down to the same problems above, more or less:

    1. This is probably completely useless. Plus, you know it would end up there every day of the week.
    2. What? Ok. class already exists, filename should be part of the src value along with data-url, and whatever about the dog barking.
    3. I'm sure this means something to someone. (If it weren't a contrived example.)
    4. Absurdity, square.

    It's hard for me to give an explicit set of ignorant and face-palm worthy malapropisms. The worst I can think of is going data--happy and cramming every. single. element. On the page. With data-. Not just horribly chatty and a waste of bandwidth in unskilled hands.


    So after all that, what to do? It's all about how you approach it. Consider:

    1. It's not for every problem remotely data-fied. At a minimum and by spec (imagine finger wagging here), if it fits in another attribute, it's not data--viable. If it's structured around a widely-accessible and standardized format promulgated by an expert or system, it's a microformat and thus is not data--land anymore.

    For instance:

    <div class="vcard">
        <span class="fn">Sally Ride</span>
        (<span class="n">
            <span class="honorific-prefix">Dr.</span>
            <span class="given-name">Sally</span>
            <abbr class="additional-name">K.</abbr>
            <span class="family-name">Ride</span>
            <span class="honorific-suffix">Ph.D.</span></span>),
        <span class="nickname">sallykride</span> (IRC)
        <div class="org">Sally Ride Science</div>
        <img class="photo" src="http://example.com/sk.jpg"/>
        <a class="url" href="http://sally.example.com">w</a>,
        <a class="email" href="mailto:[email protected]">e</a>
        <div class="tel">+1.818.555.1212</div>
        <div class="adr">
            <div class="street-address">123 Main st.</div>
            <span class="locality">Los Angeles</span>,
            <abbr class="region" title="California">CA</abbr>,
            <span class="postal-code">91316</span>
            <div class="country-name">U.S.A</div></div>
        <time class="bday">1951-05-26</time> birthday
        <div class="category">physicist</div>
        <div class="note">1st American woman in space.</div>
    </div>
    

    That's a person's description microformatted in hcard. It can and probably is usually quite a bit less verbose, but this makes a point. Take a close, notice how the use of classes and lack of data- attributes?

    Though data-fying in a meaningful way is empowering, don't pepper every cotton-pickin' piece of markup with a shotgun approach to embedding any and all maybe-maybe-not piece of data in your content. It doesn't, and it shouldn't, have to be that way. Resist that urge.

    1. Use it judiciously. When you come across some kind of listing that's incredibly extensive (like a list of clients for a medium-sized company spanning twenty years), don't push all of that into the page and expect all browsers to handle 20,000 rows of data--fied client detail asides. It's not a comprehensive data store, in other words. When necessary or appropriate, use AJAX, or a round trip, or whatnot.

    2. Modern browsers with modern hardware and modern browsers (yes, even IE8, IE7 no) can handle a sizable amount of markup fairly easily (especially Chrome). That doesn't mean, though, you shouldn't find ways to minimize that size or strategize away from 3mb HTML documents.

    3. If you overuse and overdo it, you could find yourself in a headache of too many attributes to manage easily. Use data- with a purpose. Again, judicious management and a clear focus on what's needed should help you manage any urge to bloat the content with unseen bytes of possibly unused (or inaccessible) nibbles of data here and there.

    I've leave you with this:

    A word of warning

    As data attributes become more widely used, the potential for clashes in naming conventions becomes much greater. If you use an unimaginative attribute name such as data-height, then it is likely you will eventually come across a library or plugin that uses the same attribute name. Multiple scripts getting and setting a common data- attribute will probably cause chaos. In order to avoid this, I encourage people to choose a standard string (perhaps the site/plugin name) to prefix all their data- attributes — e.g. data-html5doctor-height or data-my-plugin-height.

    http://html5doctor.com/html5-custom-data-attributes/