user5243421 user5243421 - 1 month ago 9
HTML Question

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.

Answer

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.