XJDHDR
XJDHDR

Reputation: 604

Import <head> elements from another text file with html or client-side scripting

I am currently cleaning up a website's code. I've noticed that the head elements for every page is virtually identical. I would like to know if it is possible to put all the elements that are identical into a single text file then, in every html file, import the contents of that text file in some way.

I know that you can use object to accomplish this if the common code is in the body section but this doesn't work for head.

One more thing is that these web pages are hosted on GitHub Pages, so I can only use static pages and client-side scripting. If server-side scripting is available you can, for example, use php import to accomplish this.

If it helps, this is the common code I want to import into every page:

<meta name="description" content="A central resource for PC optimization information."/>
<meta name="keywords" content="Technology,PC,Computer,Optimization,Tweak,Guide,Tweaking,Microsoft,Windows,Nvidia,Intel,AMD"/>

<link rel="stylesheet" type="text/css" media="all" href="pi.css"/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<meta name="MSSmartTagsPreventParsing" content="true"/>
<meta name="referrer" content="no-referrer"/>

<!-- Icons -->
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png?v=20191102"/>
<link rel="apple-touch-icon" href="apple-touch-icon.png?v=20191102"/>
<link rel="mask-icon" href="safari-pinned-tab.svg?v=20191102" color="#5bbad5"/>
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png?v=20191102"/>
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png?v=20191102"/>
<link rel="shortcut icon" href="favicon.ico?v=20191102"/>
<link rel="manifest" href="site.webmanifest?v=20191102"/>
<meta name="msapplication-TileColor" content="#2d89ef"/>
<meta name="theme-color" content="#ffffff"/>

Upvotes: 1

Views: 794

Answers (1)

XJDHDR
XJDHDR

Reputation: 604

With the comments above and some research on my end, I managed to come up with the following scripts to add elements to the webpage's head. One requires JQuery and the other uses vanilla JavaScript:

JQuery:

$(function(){
	$("head").load("../../aa_common_resources/common_head_elements.txt")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Vanilla JS:

var externaltextfile = '../../aa_common_resources/common_head_elements.txt'
var request = new XMLHttpRequest();
request.open('GET', externaltextfile, true);

request.onload = function() {
	document.getElementsByTagName("head").item(0).insertAdjacentHTML('beforeend', request.responseText);
   };
request.send();

Upvotes: 2

Related Questions