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

257,160

Solution 1

You can select it and add to it as normal:

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

Solution 2

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

Solution 3

jQuery

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

JavaScript:

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

Solution 4

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.

Solution 5

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

Share:
257,160
Jitendra Vyas
Author by

Jitendra Vyas

Hi, I am Jitendra a front-end developer from India specializing in web standards, accessibility, and usability based development.

Updated on January 21, 2022

Comments

  • Jitendra Vyas
    Jitendra Vyas over 2 years

    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" />
    
  • Jitendra Vyas
    Jitendra Vyas over 14 years
    how can i control order , where this link will be placed
  • nickf
    nickf over 14 years
    Read the documentation: docs.jquery.com/Manipulation insertBefore, insertAfter is what you want.
  • fredrik
    fredrik over 14 years
    dosen't appendChild require a DOM-element? ie. var elem = document.createElement() document.getElementsByTagName('head')[0].appendChild( elem );
  • David Hedlund
    David Hedlund over 14 years
    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.
  • serpent403
    serpent403 about 12 years
    I have put this in document.ready, but it doesn't append to my head contents
  • Pankaj Tiwari
    Pankaj Tiwari almost 12 years
    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?
  • Bernhard Hofmann
    Bernhard Hofmann over 11 years
    @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.
  • Quentin
    Quentin over 10 years
    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.
  • Dave
    Dave over 10 years
    for this reason you should use before $('head').html() to recover all the DOM properties
  • Quentin
    Quentin over 10 years
    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).
  • Dave
    Dave over 10 years
    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 IE11
  • Eldho
    Eldho over 10 years
    i couddn't find the attached html using firebug or chrome dev tools. how to know whether its appended or not.
  • Pingwin Tux
    Pingwin Tux about 10 years
    @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.
  • Klaider
    Klaider over 8 years
    Things that may be removed are events also.
  • mb897038
    mb897038 about 8 years
    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?
  • Marat Tanalin
    Marat Tanalin about 8 years
    AFAICT, you have exactly those elements in your Ajax response. Don't you?
  • mb897038
    mb897038 about 8 years
    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.
  • Marat Tanalin
    Marat Tanalin about 8 years
    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.
  • Ray Foss
    Ray Foss over 7 years
    Works with script elements!
  • Gaetan L.
    Gaetan L. about 4 years
    What does while (temp.firstChild) ? (sorry about the necropost)
  • Marat Tanalin
    Marat Tanalin about 4 years
    @GaetanL. “While there are child elements inside the temp element.” See Node.firstChild() docs.
  • Crhistian Ramirez
    Crhistian Ramirez over 3 years
    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 element
  • nickf
    nickf over 3 years
    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); ```
  • Harendra Chauhan
    Harendra Chauhan about 3 years
    You can also use document.head.innerHTML += '<link rel="stylesheet>...' Just Short of your Code