How to inject scripts in Hexo?
Hexo reads scripts that are stored under a
scriptsfolder in your root folder.
The Reason why I adding this tutorial:
Note: I am not sure, but seems like njk files from
source/_data/only support first<script>tag. Ofcourse you can have only one<script>tag in the njk file, and from the just use one script to run multiple scripts. But for me it is not an elegant way.
Prerequisite:
hexo-theme-nextinstalled.
Steps
-
Nextallows additional injects beside those preset incustom_file_pathfrom next config file. Read how custom_file_path works. -
Create a
scriptsfolder in your root folder. -
Add a
any_name.jsscript file. In this example I will named itinject.js. -
Add following codes into
inject.js.
"use strict";
hexo.extend.filter.register('theme_inject', function(injects) {
// Name path etc. can be modified at will, in order to facilitate the following are based on the definition here
injects.head.file('click_effect', 'source/_data/click_effect.njk', {}, {cache: true});
// the `head` from `injects.head` == the <head> tag in html
});- Do note that I am using
hexo-theme-nextin my project. So the following code only works for next theme. If you are working with other theme, you should be able to directly inject script into hexo.
- Add a new
.njkfile undersource/_data/folder. If you don’t have_datafolder, just create one.
<script type="text/javascript" src="any_script.js"></script>