Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending base tag to head with JavaScript

Can you append a base tag to the head of a document from a div in the body of the document using JavaScript? By that, I mean, what are some drawbacks of doing that? My concern is that I'll run into a sort of race condition because the base tag is understood to exist in the head so it won't get respected if the page has already been rendered. I haven't yet experienced this problem, but I was wondering whether it should be a concern.

To be clear, I know how do this via JavaScript. My question is whether the tag will be respected/honored if it's appended to the DOM after the page loads/renders...

My code is an HTML fragment that is likely to appear in the body, but I need to set the base tag because my assets are referenced relatively. Let's assume that I can't change that (because I can't. At least, not right away). You can also assume that setting the base won't break anything that's not my HTML fragment and that there are no other base tags...ever.

like image 971
user5243421 Avatar asked Jun 01 '13 02:06

user5243421


People also ask

How do I append a head tag?

Any new content can be added to this element by using the appendChild() method. The content to be added can be first created using the createElement() method and the required properties can be assigned to it. The appendChild() method appends this created element to the head of the document.

Does JavaScript go in the head tag?

The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

Where do you put the base tag?

The <base> tag must have either an href or a target attribute present, or both. There can only be one single <base> element in a document, and it must be inside the <head> element.

What is the use of base href?

Definition and Usage The href attribute specifies the base URL for all relative URLs on a page.


2 Answers

Yes, for example:

<script>
var base = document.createElement('base');
base.href = 'http://www.w3.org/';
document.getElementsByTagName('head')[0].appendChild(base);
</script>

I don’t see why you would want to do this, but it’s possible.

like image 94
Jukka K. Korpela Avatar answered Sep 28 '22 00:09

Jukka K. Korpela


I might be wrong (or partially wrong depending on how each browser chose to implement that), but AFAIK the document URL base is parsed only once. By the time you append that BASE Element to the DOM it is already too late.

EDIT: Looks like I was wrong

Apparently, there is a way. But there are also downsides about search engines.

like image 42
LexLythius Avatar answered Sep 28 '22 00:09

LexLythius