- How do I insert a script tag in to the top/beginning of head tag?
- 3 Answers 3
- Node: insertBefore() method
- Syntax
- Parameters
- Return value
- Exceptions
- Example
- Example 1
- Example 2
- Example 3
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Place ‘script’ before the end of BODY tags with jQuery
- Javascript — Insert element at script position
- 5 Answers 5
- How to insertBefore() element in body tag?
- 4 Answers 4
- Modern Solution — prepend
- Related DOM methods
How do I insert a script tag in to the top/beginning of head tag?
I want to insert a script tag before all the rest of the scripts in the head tag. How would I do that with native javascript?
document.getElementsByTagName("head")[0].appendChild(script);
Why do you need to insert it at the top? Since it’s being dynamically inserted, you can assume the other scripts have already loaded. Therefore, placing it at the top of the HEAD tag wouldn’t matter.
The script I am inserting is jquery and there is a script in the head that requires jquery and I get an error in console say «jquery is not defined» and that script won’t load.
@Justin Then this will not help, you are loading in jQuery too late as the other script has failed to find it and stopped running. Why not just add the script tag in there without javascript?
3 Answers 3
var head = document.getElementsByTagName("head")[0] head.insertBefore(script, head.firstChild);
You could explain the code I guess, provide links to docs, description of how it works. I didn’t -1, just taking a guess.
FYI, this accomplishes what the OP asked for, but doesn’t result in anything different than using appendChild() because the other scripts have already executed so putting a new one before them vs. after them doesn’t change anything. My guess is that the OP is mistaken about thinking that this will solve a problem for them.
@TheZ, jfriend00: I’m certain this is likely an X/Y Problem. The stubborn part of me likes to answer the direct question, and let them live with the result of not asking about the actual problem.
Node: insertBefore() method
The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.
If the given node already exists in the document, insertBefore() moves it from its current position to the new position. (That is, it will automatically be removed from its existing parent before appending it to the specified new parent.)
This means that a node cannot be in two locations of the document simultaneously.
Note: The Node.cloneNode() can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode() will not be automatically kept in sync.
If the given child is a DocumentFragment , the entire contents of the DocumentFragment are moved into the child list of the specified parent node.
Syntax
insertBefore(newNode, referenceNode)
Parameters
The node before which newNode is inserted. If this is null , then newNode is inserted at the end of node’s child nodes.
Note: referenceNode is not an optional parameter. You must explicitly pass a Node or null . Failing to provide it or passing invalid values may behave differently in different browser versions.
Return value
Returns the added child (unless newNode is a DocumentFragment , in which case the empty DocumentFragment is returned).
Exceptions
Example
Example 1
div id="parentElement"> span id="childElement">foo barspan> div> script> // Create the new node to insert const newNode = document.createElement("span"); // Get a reference to the parent node const parentDiv = document.getElementById("childElement").parentNode; // Begin test case [ 1 ] : Existing childElement (all works correctly) let sp2 = document.getElementById("childElement"); parentDiv.insertBefore(newNode, sp2); // End test case [ 1 ] // Begin test case [ 2 ] : childElement is of Type undefined sp2 = undefined; // Non-existent node of id "childElement" parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node // End test case [ 2 ] // Begin test case [ 3 ] : childElement is of Type "undefined" (string) sp2 = "undefined"; // Non-existent node of id "childElement" parentDiv.insertBefore(newNode, sp2); // Generates "Type Error: Invalid Argument" // End test case [ 3 ] script>
Example 2
div id="parentElement"> span id="childElement">foo barspan> div> script> // Create a new, plain element let sp1 = document.createElement("span"); // Get the reference element let sp2 = document.getElementById("childElement"); // Get the parent element let parentDiv = sp2.parentNode; // Insert the new element into before sp2 parentDiv.insertBefore(sp1, sp2); script>
Note: There is no insertAfter() method. It can be emulated by combining the insertBefore method with Node.nextSibling .
In the previous example, sp1 could be inserted after sp2 using:
.insertBefore(sp1, sp2.nextSibling);
If sp2 does not have a next sibling, then it must be the last child — sp2.nextSibling returns null , and sp1 is inserted at the end of the child node list (immediately after sp2 ).
Example 3
Insert an element before the first child element, using the firstChild property.
// Get the parent element let parentElement = document.getElementById("parentElement"); // Get the parent's first child let theFirstChild = parentElement.firstChild; // Create a new element let newElement = document.createElement("div"); // Insert the new element before the first child parentElement.insertBefore(newElement, theFirstChild);
When the element does not have a first child, then firstChild is null . The element is still appended to the parent, after the last child.
Since the parent element did not have a first child, it did not have a last child, either. Consequently, the newly inserted element is the only element.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
Place ‘script’ before the end of BODY tags with jQuery
You need the content script to do the insert on every page you want.
The code of the content script is really simple and doesn’t need jQuery.
var code = "your script code here"; var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.appendChild(document.createTextNode(code)); document.body.appendChild(script);
As it will only be called once you don’t even need to define a function. You can debug the code using debugger on any web the content script is attaching ( F12 ) you will see your code in the content script tab.
I had the same issue regarding the best place to add jQuery: to the header or before the body tag? The answer is that it does not matter.
The whole page (or DOM) needs to initialize or load in order to accomplish what you are doing.
The more information within the body, the more reliance you need to make sure the document is loaded.
The two sentences above are redundant because:
All jQuery UI, basic syntax, widgets, etc. are triggered with:
The code above means that the the full HTML page (or ‘document’) needs to be loaded before jQuery can run, AKA initialized.
There is an order that jQuery needs to be loaded for a UI to work. The actual library needs to be first, then the UI. The library can be downloaded from jquery.com and uploaded to the designers web space or through a CDN (content display network) to save on bandwidth. Here is an example of how the order should be:
Notice the library is the first line, and then the UI. In this case I loaded jQuery Mobile.
In conclusion, it does not matter. It is a preference mostly. More in on Unclear where $(document).ready goes.
Javascript — Insert element at script position
@vijay4vijju there is no particular event there. I’m just curious on how most of javascript embeds works, like they embed a video player or a chat.
5 Answers 5
You can use insertBefore method. Something like this:
var div = document.createElement('div'), // Create a new div script = document.scripts[document.scripts.length - 1]; // A reference to the currently running script div.innerHTML = 'Hello'; // Add some content to the newly-created div script.parentElement.insertBefore(div, script); // Add the newly-created div to the page
A live demo at jsFiddle. Notice, that you can use external scripts as well.
Yes this answers my question. Thank you! So script = document.scripts[document.scripts.length — 1] is needed in order to determine the parent element of the script
@DanielHyuuga Actually document.scripts is a collection of all scripts within the document. This collection is updated every time a new script is loaded/parsed during the page parsing. This way the last member of the collection always refers to the currently running script, if it is not loaded asynchronously. script.parentElement refers to the element containing the script tag itself.
When running an asynchronoulsy loaded script, the last member of document.script might refer to a different script. As long as the script itself is loaded synchronously, you can rely it finds «himself» as a last member of document.scripts . This means really running the script immediately after load, in event handlers you can’t rely on this. You could put the lines above into an IIFE, that’ll make sure the lines are executed, and also keeps some unnecessary variables out of the global namespace.
How to insertBefore() element in body tag?
But that would add the last p element just before the close of the body tag, how could I use it so it will be added to the top when it opens? So the last element added will be the first element inside the body tag. I tried:
document.body.insertBefore(p, document.getElementsByTagName('body')[0]);
Try out document.body.prepend. Also, it is generally good practice to not set innerHTML. Use oldNode.replaceWith(newNode) or set oldNode.innerText
4 Answers 4
You can get the first child of the body element with the firstChild property. Then use it as the reference.
const p = document.createElement("p"); p.textContent = "test1"; document.body.insertBefore(p, document.body.firstChild);
I modernized your code for reasons 🙂
@Persijn It was for an example only, and back in 2011 you had to use textContent or innerText in IE, so this was more convenient.
Don’t we answers question for the community? And not for a single user? We are not a helping service.
Modern Solution — prepend
This is vanilla JS and is more readable than previous options. It is currently available in all modern browsers.
You can directly prepend strings, although they won’t be ‘p’ tags
Related DOM methods
You have to insert before something. document.getElementsByTagName(‘body’)[0] is the body element (the syntax is a bit of a trick to get the body element in all browsers) 1 . If you want to insert into the body, you want to insert before the first element of it. That could look like this:
var body = document.body || document.getElementsByTagName('body')[0], newpar = document.createElement('p'); newpar.innerHTML = 'Man, someone just created me!'; body.insertBefore(newpar,body.childNodes[0]);
1 in some browsers it’s document.body , other document.documentElement etc., but in all browsers the tagname is body