Add JavaScript to Hexo Blog

Introduction

Sometimes, we would like to embed some JavaScript applications in our Hexo blog posts. In this blog post, I would like to briefly discuss it.

Procedures

  1. Create a directory for storing JavaScript scripts such as javascript, just like the directory for images, in Hexo under the source directory.
  2. Make all the content in the JavaScript directory to skip the Hexo rendering by configuring the _config.yml file.
    _config.yml
    1
    2
    skip_render:
    - "javascript/**"
  3. Insert HTML code to blog Markdown files to run JavaScript scripts.

Examples

Catch the Cat

Some Javascript applications are only running in one or a few simple canvas, running JavaScript alone in the Hexo blog becomes feasible.

For example, we have downloaded the Catch the Cat game to the javascript directory under the Hexo source directory. In this blog Markdown, we created the following HTML code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div style="text-align: center; width: 100%; border: 1px solid black;" >
<script src="/javascript/catch-cat/phaser.min.js"></script>
<script src="/javascript/catch-cat/catch-the-cat.js"></script>
<div id="catch-the-cat"></div>
<script>
window.game = new CatchTheCatGame({
w: 11,
h: 11,
r: 20,
backgroundColor: 0xffffff,
parent: 'catch-the-cat',
statusBarAlign: 'center',
credit: 'github.com/ganlvtech'
});
</script>
</div>

We could then play the Catch the Cat game in the following demo.

2048

Some JavaScript applications are tightly bounded with HTML, running JavaScript alone in the Hexo blog usually does not work well. In this case, using iframe for HTML might just be a better option.

For example, we have downloaded the 2048 game to the javascript directory under the Hexo source directory. In this blog Markdown, we created the following HTML code.

1
2
<iframe src="/javascript/2048/index.html" width="100%" height="1000" style="border:1px solid black;">
</iframe>

We could then play the 2048 game in the iframe in the following demo without compromising anything.


Alternatively, the game could also be accessed via URL.

Author

Lei Mao

Posted on

03-07-2022

Updated on

03-07-2022

Licensed under


Comments