public
Description: Keep per-element metadata in HTML comments.
Homepage:
Clone URL: git://github.com/jamespadolsey/commentData.git
commentData / commentdata.js
100644 69 lines (50 sloc) 1.831 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* commentData
* Author: James Padolsey
*/
 
var commentData = (function(){
    
    var getAllComments = function(context) {
        
            var ret = [],
                node = context.firstChild;
            
            if (!node) { return ret; }
            
            do {
                if (node.nodeType === 8) {
                    ret[ret.length] = node;
                }
                if (node.nodeType === 1) {
                    ret = ret.concat( getAllComments(node) );
                }
            } while( node = node.nextSibling );
            
            return ret;
            
        },
        cache = [0],
        expando = 'data' + +new Date(),
        data = function(node) {
            
            var cacheIndex = node[expando],
                nextCacheIndex = cache.length;
     
            if(!cacheIndex) {
                cacheIndex = node[expando] = nextCacheIndex;
                cache[cacheIndex] = {};
            }
     
            return cache[cacheIndex];
        
        };
    
    return function(context) {
        
        context = context || document.documentElement;
            
        if ( data(context) && data(context).commentJSON ) {
            return data(context).commentJSON;
        }
    
        var comments = getAllComments(context),
            len = comments.length,
            comment, cData;
            
        while (len--) {
            comment = comments[len];
            cData = comment.data.replace(/\n|\r\n/g, '');
            if ( /^\s*?\{.+\}\s*?$/.test(cData) ) {
                try {
                    data(comment.parentNode).commentJSON = (new Function('return ' + cData + ';'))();
                } catch(e) {}
            }
        }
        
        return data(context).commentJSON || true;
        
    };
    
})();