Inject Partial HTML Updates Without Refreshing The Whole Page – htmz

Category: Javascript , Recommended | February 21, 2024
Author:Kalabasa
Views Total:97 views
Official Page:Go to website
Last Update:February 21, 2024
License:MIT

Preview:

Inject Partial HTML Updates Without Refreshing The Whole Page – htmz

Description:

htmz is a lightweight JavaScript snippet that enables dynamic loading of HTML fragments into any element on a web page.

It leverages iframes and onload handlers to fetch and inject partial HTML updates, avoiding full page reloads.

htmz brings component-like behavior to plain HTML sites, enabling tabbed interfaces, modal dialogs, and other modular UI patterns without dependencies or bundling.

How it works:

htmz works by proxying requests through a special iframe named “htmz”.

When you load a URL into this iframe, the onload handler extracts a destination selector from the hash fragment and transplants the iframe’s contents into your specified element.

This allows updating a portion of the page by just linking to an HTML page.

How to use it:

1. Copy and insert the code snippet into your document. That’s it.

<iframe hidden name=htmz onload="setTimeout(()=>document.querySelector(contentWindow.location.hash||null)?.replaceWith(...contentDocument.body.childNodes))"></iframe>

2. Here is a simple tabs UI example. The structure is very similar to an <a href=”iframe.html” target=”_blank“>iframe implementation, except now the container can have a dynamic size and the content uses the same context and styles as the main page. Back navigation & history works. Because these are native HTML links (&lt;a&gt;) that work normally. No listeners, no JS, no hijacking of normal web browser web browsing.

<div role="tablist">
  <a class="tab" href="dog.html#my-tab-panel">Dog</a>
  <a class="tab" href="cat.html#my-tab-panel">Cat</a>
  <a class="tab" href="horse.html#my-tab-panel">Horse</a>
</div>
<div id="my-tab-panel" role="tabpanel"></div>

You Might Be Interested In:


Leave a Reply