include HTML code inside HTML pages using a custom tag
load-htmlto load content dynamically
- Load HTML snippets from remote URLs, recursively.
- Can be used to load Web Components, as an alternative to HTML imports: see Web Components Template example.
- Supports IE 10.
See usage example folder or read below.
Start with your index.html
load-html usage exampleLoading...
<load-html> custom HTML tag is optional.
Create files helloWorld.html and linkToHomepage.html in the same folder.
<!-- helloWorld.html -->Hello World
<!-- linkToHomepage.html -->This content was loaded by load-html.
loadHtml function some how, for example, add the following tag
to your index.html:
Then invoke it on window load, for instance add the following snippet to your index.html:
You can pass an optional callback function as argument:
- It will be executed when
<load-html />nodes are loaded.
- Loaded nodes will be passed as first argument.
- Note that loading is recursive, hence callback function could be executed more than once.
NOTA BENE The
nodes argument passed to callback is a NodeList.
NodeListis not an
Array, it is possible to iterate over it with
For example, using something like
nodes.filter(node => !node.getAttribute('error')) will fail.
However you may want to filter those nodes that did not loaded correctly. Do something like
Start with attribution comment: web site and license.
//// License: MIT
Just define a global loadHtml function.
<load-html /> tags. Note the loaded attribute is used to achieve recursive loading.
var nodes = document;var toBeLoaded = nodeslength;
Fetch the HTML content for each node.
Keep track of number of DOM nodes loaded, then try to repeat recursively. Invoke callback, if any.
toBeLoaded--;if toBeLoaded == 0if typeof callback == 'function';});
Send request to fetch content.
Store error, mark include as loaded.
} catch econsole;node;node;})}
Export it as a global function.
windowloadHtml = loadHtml;