Search code examples
javascripthtmlincludeheadw3.js

how do i use w3.js to include snippets in the head tag


With w3.js file it is possible to include html snippets into another html file similar to what we see in php but the downside is that this only works in the body of the page. e.g.

<body> 
<div w3-include-html="./src/nav.html"></div>
<script>w3.includeHTML();</script>
.
.
.
</body>  

My question now: Is there anyway to make this work in the head tag? So that one doesn't have to repeat the same block of multiple links on every single page?


Solution

  • W3.js can include elements in the head as well as the body.

    I created a quick test to be sure, and it works using:

    <html>
        <head>
            <title>Include Test</title>
            <link w3-include-html="head_include.html"/>
        </head>
        <body>
            <h1>This is a test</h1>
            <div w3-include-html="body_include.html"></div>
        </body>
        <script src="w3.js"></script>
        <script>w3.includeHTML();</script>
    </html>
    

    Here it is using the W3.js include HTML functionality to add a stylesheet in to the link tag.

    However:

    • This won't work for "file://" if you are working on this locally, because it is using an AJAX call, and the CORS policy may block it.
    • This is relying upon a Javascript executing on the page, altering the DOM, so this won't work if Javscript is disabled on the client, as it will be on things like web crawlers.
    • Unlike the php includes this is visible to the client.

    There are lots of templating alternatives, if that is your goal, and you may wish to look into Server-Side Includes if PHP is not available on your hosting solution, as this will allow you to perform inclusion of HTML with a properly configured server.