How to add anything in <head> through jquery/javascript?
Asked Answered
S

8

128

I'm working with a 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" />
Submission answered 14/12, 2009 at 13:17 Comment(6)
This doesn't make sence... The head is parsed prior to the execution of javascript. Adding meta stuf to the head via javascript would not have the desired effect.Ipa
@Mickel - yes. answers of all questions helps meSubmission
While not related to the CMS question, it can make sense to add meta tags in certain circumstances. There are various browser addons and javascript injections that use data that is in the meta tags to gather information. Facebook's OpenGraph is one example. Injecting meta tags into the head is needed when you don't have direct access to the originating HTML, whether by fault of a CMS or because you are writing a javascript addon/injection yourself.Mutism
Note that it's possible that adding <meta> tags dynamically will have no effect, depending on what they are and what browser is involved.Peaceful
Good point, that's what happens when one focuses too much on the problem ;-)Xantha
@AndreHaverdings It makes sense if you're trying to dynamically add a canonical url for web crawlers using something like Phantom JS, or you have something that parses your DOM other than the browser. Either way, that's not an answer to OP's question. Save that attitude for IRC.Sharasharai
A
173

You can select it and add to it as normal:

$('head').append('<link />');
Anatolian answered 14/12, 2009 at 13:19 Comment(9)
how can i control order , where this link will be placedSubmission
Read the documentation: docs.jquery.com/Manipulation insertBefore, insertAfter is what you want.Anatolian
I have put this in document.ready, but it doesn't append to my head contentsDeil
It is adding link, but link not showing in page's view Source... I can view it from browser development tools like Firebug. Can I view link in view source also?Thaw
@PankajTiwari You won't see it in the source view because the code appends it to the current document, not the original source (which was provided by the server). That's why FireBug and Chrome Dev tools are so useful.Gathering
i couddn't find the attached html using firebug or chrome dev tools. how to know whether its appended or not.Exorable
@PankajTiwari Newer Firefox versions have build in dev tools. Just hit [ctrl+shift+k] (if you didn't change shortcuts) and choose inspector. If javascript change html source, it will be highlighted for some moment.Grati
How would I append an html string? I am provided this html dynamically and don't know the structure of it ahead of time to convert it to an html elementAkanke
If you're sure the content is safe (ie: not from user input), maybe it'd work to put the content into a temporary element and then move elements into the head: ``` const tmp = document.createElement('div'); tmp.innerHTML = theStringOfDefinitelySafeHTML; for (const el of [...tmp.children]) document.head.appendChild(el); ```Anatolian
Y
158

JavaScript:

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

Make DOM element like so:

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

document.getElementsByTagName('head')[0].appendChild(link);
Ynes answered 29/11, 2011 at 19:56 Comment(1)
Works with script elements!Vashti
G
33

jQuery

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

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );
Gouache answered 14/12, 2009 at 13:20 Comment(2)
dosen't appendChild require a DOM-element? ie. var elem = document.createElement() document.getElementsByTagName('head')[0].appendChild( elem );Invalidate
well yes. i just left that part as ... because i didn't feel that was a central part of the question, and also, at the time of writing, there was no hands-on example as to what he wanted to put in head. but yes, it does need to be a DOM-element.Gouache
G
17

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.

Gonad answered 9/5, 2016 at 14:20 Comment(1)
You can also use document.head.innerHTML += '<link rel="stylesheet>...' Just Short of your CodeGreige
A
12

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().

Abode answered 9/5, 2016 at 20:3 Comment(6)
That is how I do it in the body, but can that really be done inside the head-tag? I was under the impression that the only allowed tags where base, link, meta, title, style and script?Xantha
AFAICT, you have exactly those elements in your Ajax response. Don't you?Abode
Indeed, but I still can't make it work with a div inside the head tag. It seems like Chrome is "smart" enough to display the content of the div in the body anyway.Xantha
You've probably not read the answer carefully. ;-) The DIV element is just a temporary container for the purpose of parsing HTML code. You shouldn't insert the DIV itself to the HEAD. You should insert its child nodes. Please see the example I've added to the answer.Abode
What does while (temp.firstChild) ? (sorry about the necropost)Paction
@GaetanL. “While there are child elements inside the temp element.” See Node.firstChild() docs.Abode
L
11

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);
Lowndes answered 25/3, 2014 at 12:17 Comment(0)
T
5

Try a javascript pure:

Library JS:

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

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

or jQuery:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));
Tunable answered 24/3, 2016 at 11:57 Comment(0)
F
-6

With jquery you have other option:

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

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

Fabiolafabiolas answered 14/12, 2013 at 11:43 Comment(5)
That will delete the existing content and generate new elements. This can have undesirable side effects such as losing dynamically set DOM properties and causing scripts to be re-executed.Pentarchy
for this reason you should use before $('head').html() to recover all the DOM propertiesFabiolafabiolas
Using .html() won't recover all the DOM properties. (The most common instance of this problem, and the most visible, is when using similar code to add new fields to a form. The value attribute represents the default value of a field, so getting html() and then setting it back will reset all the existing fields to their default values).Pentarchy
I can sure you I tested it in my code and it is working and all the DOM properties Works. Please, test yourself, I am working IE11Fabiolafabiolas
Things that may be removed are events also.Lilt

© 2022 - 2024 — McMap. All rights reserved.