how to add anything in <head> through jquery

2020-01-26 04:55发布

Working with CMS, which prevents editing HTML source for <head> element.

For example I want to add the following above the <title> tag:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

9条回答
Luminary・发光体
2楼-- · 2020-01-26 05:35

Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:

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);
}

Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.

Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().

查看更多
混吃等死
3楼-- · 2020-01-26 05:37

JavaScript:

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

Make DOM element like so:

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

document.getElementsByTagName('head')[0].appendChild(link);
查看更多
地球回转人心会变
4楼-- · 2020-01-26 05:41

You can select it and add to it as normal:

$('head').append('<link />');
查看更多
该账号已被封号
5楼-- · 2020-01-26 05:41

In the latest browsers (IE9+) you can also use document.head:

Example:

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);
查看更多
淡お忘
6楼-- · 2020-01-26 05:41

You can use innerHTML to just concat the extra field string;

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

However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.

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.

查看更多
孤傲高冷的网名
7楼-- · 2020-01-26 05:43

i don't know why i hate using jquery. i gave head an id of 'head'.

<head id="head">
<meta charset="utf-8">
 <title></title>
</head>




<script type="text/javascript">
    var head = document.getElementById('head');
    if (window.screen.width<800) {
      head.innerHTML = "  <link rel='stylesheet' href='../css/gallerys.css?ver=1.2'>";
    }else {
      head.innerHTML="<link rel='stylesheet' href='../css/gallerys.css?ver=1.3'>";
    }
</script>
查看更多
登录 后发表回答