jQuery Document Meta Plugin

April 9th, 2010

Got some persistent variables you want to pass from the server-side into your jQuery application? If you’ve got lots of complex data then you probably want to pull it in as JSON data, but for a handful of scalar variables it can be nice to just output them in the document head as meta tags.

<meta name="user_id" content="1337" />
<meta name="user_name" content="Gary Barlow" />

I’m thinking core stuff like user ids which never change and get used again and again in ajax calls. Yes, you could achieve the same thing with cookie data, but if like me you like to keep the amount of data stored in cookies to the bare minimum, then this can be a nice little solution.

You can easily access these values like this:

var user_id = $("meta[name='user_id']").attr('content')

But eww, it’s pretty ugly, and ugly code makes Jamie a sad developer.

The following plugin simply provides a neat shorthand for accessing those variables. And I do like to keep things neat. It also caches by means of lazy-loading each meta contents into an internal object, so that the DOM is only traversed once. This is possibly overkill, and probably doesn’t save a single millisecond in any real-life scenario, but I like to optimise as I go and you can’t stop me.

(function($) {
$.meta = function(name) {
    if (typeof($.meta.cache[name])=='undefined'){
        $.meta.cache[name] = $("meta[name='"+name+"']").attr('content');
    }
    return $.meta.cache[name];
};
$.meta.cache = new Object;
})(jQuery);

You’re then free to access your variables neatly and concisely throughout your application using your new $.meta function.

$.post('path/to/someAjaxController', {method: 'doStuff', id: $.meta('user_id')}, function(r){
    alert('Thanks for doing stuff ' + $.meta('user_name'));
})

This isn’t to be confused with the existing and widely used jQuery Metadata Plugin which extracts meta data from DOM Elements. I should perhaps call this plugin something different, but to be honest I can’t think of a better name.

So to sum up. Ground-breaking? Not really. Useful? Yes.

Posted in Web | Tagged with: , ,

3 Responses

  1. Montana Flynn

    Excellent plugin and idea. Thanks.

  2. Gerard

    Useful plugin!
    The new HTM5 data attributes (http://ejohn.org/blog/html-5-data-attributes/) are useful at the element level, but I like the idea of using meta tags + jQuery to store global data.

  3. bird

    nice plugin..

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.