How bad of an idea: using JavaScript to define HTML <head>

I want the JavaScript to define the document’s head. How unclever am I?
Did the science gone too far? Shall we reinvent time machine?

<!DOCTYPE html>
<html lang="en">
	<head>
		<script>
			Document.characterSet = "UTF-8";
			Document.title = "A New Page";
		</script>
	</head>
	<body>
		<header>
		</header>
		<main>
		</main>
		<footer>
		</footer>
	</body>
</html>


Why do you want to do this?

The Idea is to load head from a json file for every web page I have.
So that in the future it would be easier to do a “groundbreaking” change across all the pages.
Or should I just use some kind of hardcore preprocessor like PHP since it is a very bad idea?

Do it in **<body>**, it will be faster…

You can’t really define the entire head (there are things that have to load first prior to the JS). And if you have a web site with a set number of pages, this is probably not actually going to simplify things. By all means go for it, you’ll learn a lot. There are a lot of problems with this approach but you aren’t likely to understand why they are problems unless you try it.

If it is a web site with many pages (maybe an unknown number, for example an e-commerce store or a blog), it’s not “hardcore” to use PHP (or NodeJS or Ruby or Python or C# or Java or just a prebuilt CMS like WordPress) it’s generally much simpler than what you’re trying to do. You need to be in control of the server anyway, so why serve web pages then do some complex JS shenanigans when you could just serve the web pages?

Notice I’m specifying web site. If it is a single page app where the different pages are just basically a fiction created by using the browser History API, then you would use a client-side router (Google is your friend here), and you kinda need to inject stuff into the head with that approach, sort of

1 Like

If you working with templates from NodeJS like Pug/EJS or ASP.NET with cshtml you can make a layout page and re-render the body for each other template.

1 Like