From c9f27daf558827e912138cb7fc1656cecbea87b9 Mon Sep 17 00:00:00 2001 From: alefra88 Date: Mon, 6 Mar 2023 06:22:43 -0600 Subject: [PATCH] same script was added but using fetch and async/await --- include-html-async-await.js | 19 +++++++++++++++++++ include-html-fetch.js | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 include-html-async-await.js create mode 100644 include-html-fetch.js diff --git a/include-html-async-await.js b/include-html-async-await.js new file mode 100644 index 0000000..96f9d79 --- /dev/null +++ b/include-html-async-await.js @@ -0,0 +1,19 @@ +document.addEventListener("DOMContentLoaded", (e) => { + const includeHTML = async (el, url) => { + try { + const response = await fetch(url); + if (response.ok) { + const html = await response.text(); + el.outerHTML = html; + } else { + throw new Error("Error loading the file, verify that you are making the request by http or https"); + } + } catch (error) { + el.outerHTML = `

Error: ${error.message}

`; + } + }; + + document + .querySelectorAll("[data-include]") + .forEach((el) => includeHTML(el, el.getAttribute("data-include"))); +}); \ No newline at end of file diff --git a/include-html-fetch.js b/include-html-fetch.js new file mode 100644 index 0000000..a39cbed --- /dev/null +++ b/include-html-fetch.js @@ -0,0 +1,22 @@ +document.addEventListener("DOMContentLoaded", (e) => { + const includeHTML = (el, url) => { + fetch(url) + .then(response => { + if (response.ok) { + return response.text(); + } else { + throw new Error("Error loading the file, verify that you are making the request by http or https"); + } + }) + .then(html => { + el.outerHTML = html; + }) + .catch(error => { + el.outerHTML = `

Error: ${error.message}

`; + }); + }; + + document + .querySelectorAll("[data-include]") + .forEach((el) => includeHTML(el, el.getAttribute("data-include"))); +}); \ No newline at end of file