How to insert metatag without using jquery append?

左心房为你撑大大i 提交于 2019-11-29 04:21:20
var viewPortTag=document.createElement('meta');
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);

You can also use "setAttribute" (rather than the "dot" notation) for weirdo attribute names (that contain non-alpha-numeric characters).

Example:

var iefix=document.createElement('meta');
iefix.setAttribute("http-equiv", "X-UA-Compatible");
iefix.setAttribute("content", "IE=Edge");
document.getElementsByTagName('head')[0].appendChild(iefix);

The example above causes IE (<=9) to always use the latest document standards mode. Sometimes IE will fall back to older standards, and therefore break your modern javascript / canvas web app.

Javascript solution:

document.getElementsByTagName('head')[0].innerHTML += '<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">';

Here is a solution that creates a meta tag, if it does not already exist:

var viewport = document.querySelector('meta[name=viewport]');
var viewportContent = 'width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0';

if (viewport === null) {
  var head = document.getElementsByTagName('head')[0];
  viewport = document.createElement('meta');
  viewport.setAttribute('name', 'viewport');
  head.appendChild(viewport);
}

viewport.setAttribute('content', viewportContent);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!