LoginSignup
0
1

More than 5 years have passed since last update.

markdownファイルをajaxで取得してクライアント側で描画する

Last updated at Posted at 2017-10-25

やりたいこと

html/
  index.html
  index.md
  hoge.md

index.htmlから同じディレクトリのmdファイルをajaxで取得し、クライアント側でjsで処理して描画する

  • example.com にアクセス => index.md が表示
  • example.com/#hoge にアクセス => hoge.md が表示

補足

  • 使用したjs
    • syntax highlight => prism.js
    • markdown parser => marked.js
  • HTMLのページ内ジャンプが使えなくなる…

source

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/2.9.0/github-markdown.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.3/themes/prism.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.3/prism.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>
</head>
<body>
  <div class="container">
    <div id="markdown_content" class="markdown-body"></div>
  </div>

<script>
window.onhashchange = function(){
  location.reload();
}
let target = document.getElementById('markdown_content');
marked.setOptions({
  langPrefix: 'language-'
});

(async () => {
  try {
    const filename = location.hash.slice(1) || 'index';
    const response = await fetch(filename+'.md', {method: 'GET'});
    const responseText = await response.text();
    target.innerHTML = marked(responseText);
    Prism.highlightAll();
  } catch (e) {
    target.innerHTML = 'failed to load a markdown file';
  }
})();
</script>
</body>
</html>
index.md
# README

index.htmlからajaxでmdファイルを取得してパースして表示。syntax highlightにも対応

- [hoge](/#hoge)
hoge.md
# HOGE

- fuga
- piyo

\```javascript

var hoge = 'piyo';
function fuga(){
  // aaa
}
\```

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1