Table of Contents

<HTMLElement>.load()

Loads an HTML snippet into an element.

Usage:
HTMLElement = Element.load(url, options)
Member of:
HTMLElement
Parameters:
  1. url – the address to load the HTML snippet from (required).
  2. options – an Object containing options for the HTTP request, as specified for the Fetch API (optional).
Returns:
A Promise object, as returned by the fetch() global function.
Notes:
  • This is an asynchronous function, as the fetched data may only be available after a delay.
  • Security restrictions on which resources can be loaded, still apply to these requests. See CORS for more information.
  • The loaded HTML snippet is inserted into the DOM “as is”, i.e. any header elements, etc. are also loaded. The recommended approach is to provide simple snippets without unnecessary elements.
  • The loaded HTML snippets have to comply with XHTML rules (which are more strict than those for HTML5!)
    • Among others, named entities (like “&nbsp;” and unclosed elements (e.g. “<br>”) are not allowed within these files.
    • It is however possible to have multiple root elements, as the snippet will be wrapped into a temporary root element before parsing. This element is then removed before inserting the file content.
  • If the element that this is called on previously contained any child elements, these will be replaced by the loaded (X)HTML snippet.

Examples

A simple example could look like this:

document.getElementById('foo').load("bar.html");

Since this method returns a Promise object, the .then() method can be used to chain program code that is called only after the resource is loaded:

document.getElementById('foo')
   .load("bar.html")
   .then( result => {
       console.info(result);
   })
;

The .then()' method has an additional (optional) callback function, which gets called in case an error occurs:

document.getElementById('foo')
   .load("bar.html")
   .then(
      success => {
         console.info('success');
      },
      failure => {
         console.error('failure');
      }
   )
;

A better approach to error handline, however, is to use the Promise object’s .catch() and .finally() methods instead. These work similar to standard JavaScript try … catch exception handling:

document.getElementById('foo')
   .load("bar.html")
   .then()
   .catch( error => {
      console.error(error);
   })
   .finally( () => {
      console.info('done.');
   })
;

See also

More information