如何通过 jquery/javascript 在 < head > 中添加任何内容?

我使用的是 CMS,它可以防止为 <head>元素编辑 HTML 源代码。

例如,我想在 <title>标签上添加以下内容:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
272736 次浏览

您可以选择它并像往常一样添加:

$('head').append('<link />');

JQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

让 DOM 元素像这样:

const link = document.createElement('link');
link.href = 'href';
link.rel = 'rel';


document.getElementsByTagName('head')[0].appendChild(link);

使用 jquery 你还有其他选择:

$('head').html($('head').html() + '...');

anyway it is working. JavaScript option others said, thats correct too.

在最新的浏览器(IE9 +)中,你也可以使用 文件,头:

例如:

var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';


document.head.appendChild(favicon);

尝试一个纯 javascript:

图书馆 JS:

appendHtml = function(element, html) {
var div = document.createElement('div');
div.innerHTML = html;
while (div.children.length > 0) {
element.appendChild(div.children[0]);
}
}

类型: appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');

或 jQuery:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));

您可以使用 innerHTML连接额外的字段字符串;

document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'

然而,你不能保证你添加到头部的额外内容会在第一次加载后被浏览器识别出来,并且当额外的样式表被加载时,你可能会得到一个 FOUC (未样式化内容的闪现)。

I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.

创建一个临时元素(例如 DIV) ,将 HTML 代码分配给它的 innerHTML属性,然后将其 child nodes一个一个地附加到 HEAD元素。例如,像这样:

var temp = document.createElement('div');


temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';


var head = document.head;


while (temp.firstChild) {
head.appendChild(temp.firstChild);
}

与通过 innerHTML重写整个 HEAD内容相比,这不会以任何方式影响 HEAD元素的现有子元素。

注意,以这种方式插入的 剧本显然不是自动执行的,而样式是成功应用的。因此,如果需要执行脚本,应该使用 阿贾克斯加载 JS 文件,然后使用 eval()执行它们的内容。