Wyn He
Wyn He

Reputation: 51

How to add script to head tag in MkDocs?

I am new to MkDocs and I built up a website using MkDocs and I want to add some script into <head>...</head>.

I tried this code at top of my markdown file but it didn't work :

<head>
<script>
...
</script>
</head>

I found the script would show in <body>...</body> rather than in <head>...</head>.

How to place <script> in <head> tag?

Upvotes: 5

Views: 5543

Answers (5)

poundifdef
poundifdef

Reputation: 19370

In mkdocs.yml

theme:
  custom_dir: overrides

Then in overrides/main.html

{% extends "base.html" %}

{% block libs %}
  <!-- Add scripts that need to run before here -->
  {{ super() }}

  <!-- Add scripts that need to run afterwards here -->
{% endblock %}

This will let you add new scripts to the HEAD tag while maintaining everything else.

This process is documented here: https://squidfunk.github.io/mkdocs-material/customization/#overriding-blocks

Upvotes: -1

rosebud
rosebud

Reputation: 69

The extrahead placeholder, which should be present in all themes, allows additions to be made to the <head>.

You need to specify a custom_dir in the YAML file and in this directory have a main.html with an extrahead block.

See:

https://www.mkdocs.org/user-guide/customizing-your-theme/#using-the-theme_dir

Upvotes: -1

Waldemar Lehner
Waldemar Lehner

Reputation: 1075

Assuming your are using MkDocs Material as your Theme, inside your mkdocs.yml you can add Entries to the extra_javascript List.

mkdocs.yml:

site_name: "..."
theme: "..."
# ...
extra_javascript:
  - https://cdn.someCdn.someLibrary.js # Online Resource
  - js/ourJsFile.js # Path relative to "docs" Directory
# Works the same way for CSS!
extra_css:
  - css/someCSS.css # Again, relative to the "docs" Directory

For reference: https://squidfunk.github.io/mkdocs-material/customization/#adding-assets

Upvotes: -1

tieger
tieger

Reputation: 27

You can use material. in your theme (mkdocs.yml), add a reference to custom dir, and in that dir, you can add a file named main.html which will be included in the "head" part See https://squidfunk.github.io/mkdocs-material/customization/#overriding-partials for more details.

Upvotes: 1

Trang D
Trang D

Reputation: 327

Try this:

<!DOCTYPE html>
<html>
  <head>
 <script src="https://file.js"></script>
  </head>
  <body>
    {{ content }}
  </body>
</html>

Upvotes: -6

Related Questions