Skip to content

Commit

Permalink
Non-blocking fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
LordKa0S committed Jul 17, 2021
1 parent eff4589 commit bb12693
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 19 deletions.
13 changes: 5 additions & 8 deletions index.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
<div id="index-placeholder"></div>

<script>
(async () => {
const response = await fetch('index.md');
const text = await response.text();
const script = document.getElementById('helpers');
script.addEventListener('load', () => {
transformMarkdownAndReplaceId(text, 'index-placeholder');
});
})();
const responsePromise = fetch('index.md');
const script = document.getElementById('helpers');
script.addEventListener('load', () => {
transformMarkdownAndReplaceId(responsePromise, 'index-placeholder');
});
</script>

{{> partials/footer}}
8 changes: 5 additions & 3 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ const replaceWithContent = (element) => {
}

/**
* Replaces an element in the DOM with the HTML obtaining by transforming given markdown
* @param {string} text Markdown
* Replaces an element in the DOM with the HTML obtaining by transforming markdown resolved in the given Promise
* @param {Promise<Response>} responsePromise Promise resolving to markdown content
* @param {string} id id of the element in DOM to replace
*/
const transformMarkdownAndReplaceId = (text, id) => {
const transformMarkdownAndReplaceId = async (responsePromise, id) => {
const response = await responsePromise;
const text = await response.text();
const html = markdownToHtml(text);
const toReplace = document.getElementById(id);
toReplace.innerHTML = html;
Expand Down
13 changes: 5 additions & 8 deletions news.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,11 @@
{{> partials/old_news}}

<script>
(async () => {
const response = await fetch('news.md');
const text = await response.text();
const script = document.getElementById('helpers');
script.addEventListener('load', () => {
transformMarkdownAndReplaceId(text, 'news-placeholder');
});
})();
const responsePromise = fetch('news.md');
const script = document.getElementById('helpers');
script.addEventListener('load', () => {
transformMarkdownAndReplaceId(responsePromise, 'news-placeholder');
});
</script>

{{> partials/footer}}

0 comments on commit bb12693

Please sign in to comment.