Skip to content

How to use $document in custom js? #6954

Answered by squidfunk
naterichman asked this question in Q&A
Discussion options

You must be logged in to vote

You cannot use document$ inside Markdown in script tags, because it is only available at the end of the rendered page. This is because the JavaScript is initialized at the bottom of the body element (which is a best practice to improve rendering times). A better idea is to move your JavaScript into an additional file, which ensures correct order. Alternatively, you can use the following in your Markdown file (not recommended for third-party libraries):

document.addEventListener("DOMContentLoaded", () => {
  // Your code
})

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by naterichman
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants