[thelist] Adding META tag via the DOM if not already present (Javascript)

Christian Heilmann codepo8 at gmail.com
Wed Jan 30 01:54:08 CST 2008


> Probably the quickest way would be to do a regex check on innerHTML of
> the HEAD element, then you neither need to worry about the browser
> inconsistencies nor about the slowness of this approach.
>
> Just include that at the end of the BODY as the head won't be ready if
> you include it there:
>
>     (function(){
>       var head = document.getElementsByTagName('head')[0];
>       var content = head.innerHTML;
>       if(content.indexOf('name="DCSext.wt_m"') === -1 &&
>          content.indexOf('name="DCSext.wt_maglocale"') === -1){
>         // can not has metas KTHXBAI
>         var meta = document.createElement('meta');
>         meta.name = 'DCSext.wt_maglocale';
>         meta.content = 'en-uk';
>         head.appendChild(meta);
>         // ... and so on ...
>       }
>     }());
>
> http://icant.co.uk/sandbox/meta.html

That is the fastest, if you want to make sure not to have duplicates
and do a thorough check (allow for uppercase and missing or different
quotation marks) then you can do:

    (function(){
      var metas = [
        {
          name:'DCSext.wt_m',
          value:'whatever goes in there'
        },
        {
          name:'DCSext.wt_maglocale',
          value:'en-uk'
        }
      ];
      var head = document.getElementsByTagName('head')[0];
      var content = head.innerHTML;
      for(var i=0;metas[i];i++){
        if(!content.match('/name=[\"|\']?'+metas[i].name+'[\"|\']?/gi')){
          var meta = document.createElement('meta');
          meta.name = metas[i].name;
          meta.content = metas[i].value;
          head.appendChild(meta);
        }
      };
    }());

-- 
Chris Heilmann
Book: http://www.beginningjavascript.com
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/



More information about the thelist mailing list