Skip to content

Commit

Permalink
Fetch md files parallely with js
Browse files Browse the repository at this point in the history
  • Loading branch information
LordKa0S committed Jul 17, 2021
1 parent aa27c71 commit eff4589
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 20 deletions.
14 changes: 9 additions & 5 deletions index.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
<div id="index-placeholder"></div>

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

{{> partials/footer}}
{{> partials/footer}}
18 changes: 8 additions & 10 deletions lib/helpers.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/**
* Reads markdown from the given URL and tranforms it into HTML
* @param {string} filePath URL to fetch the markdown from
* Transforms markdown to HTML
* @param {string} text Markdown
* @returns {string} HTML
*/
const readMarkdown = async (filePath) => {
const response = await fetch(filePath);
const text = await response.text();
const markdownToHtml = (text) => {
marked.setOptions({
headerIds: false,
});
Expand All @@ -24,13 +22,13 @@ const replaceWithContent = (element) => {
}

/**
* Replaces an element in the DOM with the HTML obtaining by transforming markdown fetched from the given URL
* @param {string} filePath URL to fetch the markdown from
* Replaces an element in the DOM with the HTML obtaining by transforming given markdown
* @param {string} text Markdown
* @param {string} id id of the element in DOM to replace
*/
const fetchMarkdownAndReplaceId = async (filePath, id) => {
const text = await readMarkdown(filePath);
const transformMarkdownAndReplaceId = (text, id) => {
const html = markdownToHtml(text);
const toReplace = document.getElementById(id);
toReplace.innerHTML = marked(text);
toReplace.innerHTML = html;
replaceWithContent(toReplace);
}
14 changes: 9 additions & 5 deletions news.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@
{{> partials/old_news}}

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

{{> partials/footer}}
{{> partials/footer}}

0 comments on commit eff4589

Please sign in to comment.