Dynamic Inline HTML Importing with i-html Web Component

Category: Javascript , Loading , Recommended | December 11, 2024
Authorkeithamus
Last UpdateDecember 11, 2024
LicenseMIT
Views41 views
Dynamic Inline HTML Importing with i-html Web Component

The <i-html> web component allows you to dynamically import HTML content inline, similar to an <iframe>, but with the content adopted directly into the page. If you’ve used techniques like Hotwire Turbo or GitHub’s include-fragment-element, <i-html> will feel familiar.

Here’s a quick demonstration:

<i-html src="/path/to/hello.html">Loading...</i-html>

When JavaScript is enabled, the Custom Element will display “Hello world!”. The <i-html> acts as an empty container that fetches and replaces its contents with the parsed HTML from the specified source.

Under the hood, the <i-html> fetches HTML content from a specified source and injects it into the page. It remains in the DOM, allowing for repeated fetches and dynamic content updates. This makes it more versatile than elements like <include-fragment>, which replace themselves upon loading.

Use Cases:

  • Dynamic Content Updates: Update sections of your page without full reloads.
  • Modular Web Design: Break down your UI into reusable HTML components.
  • Interactive Forms: Create forms that update in place, mimicking AJAX behavior.
  • Content Targeting: Extract specific elements from a response and inject them into the page.
  • Server-Side Event Handling: Stream content updates using the text/event-stream mode.

Benefits:

  • Performance: Load content only when needed, especially with lazy loading.
  • Maintainability: Organize your HTML into smaller, manageable files.
  • User Experience: Deliver smoother, more interactive web experiences.
  • Security: Built-in safeguards to help prevent common security issues.

Case Study Examples:

  • Navigation: Use <a> tags to target and update an <i-html> element, creating dynamic navigation without page refreshes.
  • Forms: Wrap a <form> in <i-html> for a seamless form submission experience, or use formaction attributes on buttons for different actions.
  • Theming: Dynamically load different stylesheets to change the look of your site based on user preferences or other conditions.
  • List Management: Use insert attribute to append or prepend new items to a list fetched by <i-html> element.

Installation:

1. Install & download.

# NPM
$ npm install i-html-element

2. Import the i-html-element web component.

<script src="/path/tp/i-html.min.js" defer></script>
// OR
<script type="module" src="node_modules/i-html-element/i-html.js"></script>

How to use it:

1. Place an <i-html> tag on your page and set the src attribute to the URL of the HTML content you want to import.

2. See the demo page for more details like Targeting with Links, Targeting with Forms, Targeting the Response, Streaming Mode, Insertion Mode, Deferring Loading, and more.

You Might Be Interested In:


Leave a Reply