skip to Main Content

I have this _head.html file:

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weboldal modulokból</title>
<link rel="stylesheet" href="styles.css">

How can I insert the content of _head.html file into < head > tag of my index.html?

This was my solution:

<head><link rel="import" href="_head.html"></head>

but it was a wrong result.

2

Answers


  1. 1. Make sure you have both the index.html and _head.html files in the same directory.

    2. In your index.html, add an empty <head> section where you want to include the content from _head.html. You can add an id attribute to make it easier to select this element using JavaScript.

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Weboldal modulokból</title>
      <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <!-- The rest of your HTML content -->
    </body>
    </html>

    3. Add a tag just before the closing tag in your index.html to include the JavaScript code to load and insert the content from _head.html.

    <script>
      // Use JavaScript to fetch and insert content from _head.html
      fetch('_head.html')
        .then(response => response.text())
        .then(data => {
          const head = document.querySelector('head'); // Select the empty head element
          head.innerHTML = data; // Insert the content from _head.html into the head element
        })
        .catch(error => console.error('Error loading _head.html', error));
    </script>

    This JavaScript code uses the fetch API to retrieve the content of _head.html as text and then inserts it into the <head> section of your index.html.

    With this approach, you won’t need to use <link rel="import">, and it’s more in line with modern web development practices.

    Login or Signup to reply.
  2. HTML Imports are a feature that works natively only in Google Chrome. Support for HTML Imports in Google Chrome has been available since version 31, but it requires manual enabling. For further details, you can refer to the official documentation on MDN Web Docs.

    So using the Link tag should not work anymore. Example Below :

    <link rel="import" href="/path/to/some/import.html" />
    

    Instead Please try to do it in php. Here is a simple example

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <title>Basic HTML Imports</title>
        <!-- Pull in our blog post example -->
        <?php require('blog-post.html'); ?>
      </head>
      <body>
        <p>Hello World!</p>
      </body>
    </html>
    

    Make sure your index file is named Index.php, you can check the screenshot.

    Screenshot

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search