How do I import External HTML file using JavaScript and without using frames?

Dani AI

Generated

, since you want one header/menu reused across pages (no frames), the most robust approach is to render it server-side or at build time. If your pages can run through PHP, put the markup in partials/header.html and include it with <?php include __DIR__ . '/partials/header.html'; ?>. On Apache without PHP, Server Side Includes can do the same (Server Side Includes). This avoids flicker, works without JavaScript, and is friendlier to crawlers.

If you must do it with JavaScript, fetch the fragment and inject it:

<div id="site-header"></div>
<script>
  fetch('/partials/header.html', { credentials: 'same-origin' })
    .then(res => {
      if (!res.ok) throw new Error(res.status + ' ' + res.statusText);
      return res.text();
    })
    .then(html => {
      document.getElementById('site-header').innerHTML = html;
    })
    .catch(err => console.error('Header load failed:', err));
</script>

Notes and gotchas:

  • Serve the site over http(s). Loading a file via file:// or cross-origin will fail due to browser security rules (Fetch API, CORS).
  • For SEO and accessibility, prefer server-rendered nav or provide a <noscript> fallback. Google can process JS, but server-rendered content is still more reliable for critical navigation (JavaScript SEO basics).
  • To reduce layout shift, reserve space for the header or inline a small skeleton. Put a <nav role="navigation"> inside your header fragment, and set the active link per page (e.g., add a class based on the current URL).

As hinted, clarifying the goal helps. With your follow-up, server includes or a simple build step will give you the maintenance win you want with fewer trade-offs than a JS-only import.

Recommended Answers

All 2 Replies

You better explain what you trying to do...

You better explain what you trying to do...

Actually I am trying to make website, and I don't want to copy paste header and menu in every single page. I just want to make changes in one page which will automatically update all other pages if I use import method in every single pages.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.