Any other better way to include a JS/CSS file for a particular section only

How do I insert some JS/CSS files for a particular section only, like for blog section.

For JS , I am doing something like including like below with “defer” attribute in list.html or single.html layout file for blogs. “Defer” so that the script executes once the page has parsed.

<script src="/js/blogs.js" type="text/javascript" defer></script>

Question 1 : Is my above defer inclusion method in the layout files , a good solution ? Or can it be a issue for some reason ?

I found this Best way to include JavaScript libraries in Hugo sites - #2 by rhewitt solution interesting , but I guess to implement this I need to add the script or css files links to front matter of every blog .md files if I am not wrong, which I feel is redundant thing.

Question 2: Any better way you guys use for such scenerio, Kindly let me know.

I would (not tested):

  • Use the cascade option on the front-matter for desired section so you only have to do it once.
  • Use a boolean on the section front matter. Ex : local_include : true
  • Use a global Params variable in config.toml. Ex :
  js =
  css =
  • In your code (I guess this is in header) test this variable. Ex:
{{ if .Params.local_include}}
   <link rel="stylesheet" href="{{ site.Params.local_include.css }}">
   <script src="{{ site.Params.local_include.js }}"></script>
{{ end }}

You get the idea (code not tested), and you have to adapt it.


Also another way would be:
{{ if in .Section "name-of-section" }}<--- JS for that section --->{{ end }}


Thanks for answering ! Do I have to set local_include : true frontmatter on every .md files of that particular section ?

@alexandros tip is if you hard code the section. Easiest way of doing it.

My proposal is more generic.

For cascade keyword you will only put it once in the section frontmatter.

See Front Matter | Hugo

For example in content/blog/

   local_include : true
title: Blog section

And all your blog post will inherit from this.
When you want this for a new section, just add a new frontmatter parameters in the new section.