Search code examples
htmlcssresponsive-designmedia-queriesmetatag

Responsive design: meta tag loading


I'm looking to get this construction, I know it's not possible but i'm looking for an alternative way.

@media all and (min-width: 480px) {
 <meta name="viewport" content="width=device-width, initial-scale=1,
 maximum-scale=1" />
}

So basically I need this <meta /> tag to only be active on screens larger then 480px in width.

Can this be done with standard HTML or is there a jQuery sollution?


Solution

  • CSS won't be able to insert a META tag like this (you could target IE with IE specific comments but I doubt that helps you).

    You can however inject this tag dynamically using JavaScript:

    //set a flag so the meta tag doesn't get loaded more than once
    var metaLoaded = false;
    $(window).on("resize.my-meta", function () {
    
        //check if the meta tag has already been loaded, if not check the viewport width
        if (!metaLoaded && $(window).width() >= 480) {
    
            //the viewport width is at or greater than 480, so add the meta tag to the DOM
            $("head").append('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />');
    
            //set flag so we don't add the meta tag twice
            metaLoaded = true;
        }
    }).trigger("resize.my-meta");//this runs the resize event handler to setup the initial state
    

    Here is a demo: http://jsfiddle.net/5GxNH/