Skip to content

Loads the content called with Javascript Fetch() into an HTML page and triggers the scripts without any complications

License

Notifications You must be signed in to change notification settings

ranaroussi/ajax-fetch-data-loader

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Ajax Fetch() Data Loader

This small script allows you to insert HTML content and Javascript code retrieved in Ajax with the Javascript Fetch() API

Demo

https://www.ajax-fetch-data-loader.miglisoft.com

About

The Fetch() Javascript API is a simple and modern way to load dynamic content into a page. Unfortunately if the loaded content contains some Javascript code it will not be interpreted, that is why I provide this script.

Features

  • parse the content retrieved with Fetch
  • creates an Array with the HTML nodes and the scripts at the end
  • parses the Array and:
    • inserts the html nodes in the destination container
    • inserts the javascript into <script /> tags, which allows them to be executed.

Usage/Examples

<script>
    document.addEventListener('DOMContentLoaded', function(event) {
        fetch('data.html')
        .then(function (response) {
            return response.text()
        })
        .then(function (html) {
            console.info('content has been fetched from data.html');
            loadData(html, '#ajax-target').then(function (html) {
                console.info('I\'m a callback');
            });
        }).catch((error) => {
            console.log(error);
        });
    });
</script>

Alternatively you can append the fetched content to the HTML container instead of replacing it:

    // first fetch your content like in the first example above, then ...
    // the third "true" argument will append the fetched content into the container instead of replacing its original content.
    loadData(html, '#ajax-target', true).then(function (html) {
        console.info('I\'m a callback');
    });

Authors

About

Loads the content called with Javascript Fetch() into an HTML page and triggers the scripts without any complications

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 55.9%
  • HTML 44.1%