Attempting to install MetaTag dynamically

I am trying to dynamically set the meta tag to the head of my document. This is a mobile device specific meta tag that I need to add through code. I found this solution here:

Failed to use jQuery to set meta tag values

but it doesn't seem to work, what am I doing wrong?

function setOrCreateMetaTag(metaName, name, value) {
    var t = 'meta['+metaName+'='+name+']';
    var mt = $(t);
    if (mt.length === 0) {
        t = '<meta '+metaName+'="'+name+'" />';
        mt = $(t).appendTo('head');
    }
    mt.attr('content', value);
}

setOrCreateMetaTag(name, viewport, 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');
+3
source share
2 answers

Two things. First, make sure you enable jQuery since $ () is a jQuery method. This includes something like:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>    

Secondly, I don’t think you really wanted to pass the variable name and viewport. Rather, you should pass strings, for example:

setOrCreateMetaTag('name', 'viewport', 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');
+2
source

, , :

setOrCreateMetaTag('name', 'viewport', 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0');
0

Source: https://habr.com/ru/post/1762216/


All Articles