2

Is there a (simple) way to import meta data from another file in HTML?

I have tens of pages with the same header. When I add or update a link or metadata, I don't want to update every file.

After reading these answers, I tried: <link rel="import" href="/html/content.html">. It works fine for <link href= or <link rel=, but meta are not imported.

Meanwhile, I created a PHP function that echoes the headers in each page, but I would have prefer a pure HTML solution.

unor
  • 92,415
  • 26
  • 211
  • 360
Mr Robot
  • 1,037
  • 9
  • 17

1 Answers1

0

After the HTML file is imported you must inject its content in the main file.

<head>
    <script>
        function inject( import ) {
            document.head.appendChild( import )
        }
    </script>
    <link rel="import" href="/html/content.html" onload="inject(this.import)">
</head>

Alternatly, you can also put the script part in the imported file, since it's interpreted as soon as it is loaded.

Example in the content.html file:

<template>
    <script src="link1.js"></script>
    <meta name="author" value="someone">        
    ...
</template>
<script>
    var template = document.currentScript.querySelector( 'template' )
    document.head.appendChild( template.cloneNode( true ) )
</script>

Note: It's better to put all the content in a <template>, this way the content will be remain unactivated until it is inserted in the main document.

Supersharp
  • 29,002
  • 9
  • 92
  • 134