Loads an HTML snippet into an element.
load(url, options) ” and unclosed elements (e.g. “<br>”) are not allowed within these files.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.'); }) ;