mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Add JavaScript To Body Of The Document as a new Gatsby til
This commit is contained in:
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_917 TILs and counting..._
|
||||
_918 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -21,6 +21,7 @@ _917 TILs and counting..._
|
||||
* [CSS](#css)
|
||||
* [Devops](#devops)
|
||||
* [Elixir](#elixir)
|
||||
* [Gatsby](#gatsby)
|
||||
* [Git](#git)
|
||||
* [Go](#go)
|
||||
* [HTML](#html)
|
||||
@@ -187,6 +188,10 @@ _917 TILs and counting..._
|
||||
- [When Things Don't Match The With Statements](elixir/when-things-dont-match-the-with-statements.md)
|
||||
- [Word Lists For Atoms](elixir/word-lists-for-atoms.md)
|
||||
|
||||
### Gatsby
|
||||
|
||||
- [Add JavaScript To Body Of The Document](gatsby/add-javascript-to-body-of-the-document.md)
|
||||
|
||||
### Git
|
||||
|
||||
- [Accessing a Lost Commit](git/accessing-a-lost-commit.md)
|
||||
|
||||
29
gatsby/add-javascript-to-body-of-the-document.md
Normal file
29
gatsby/add-javascript-to-body-of-the-document.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Add JavaScript To Body Of The Document
|
||||
|
||||
Sometimes your JavaScript script tag needs to be placed in the body of the
|
||||
document. Like inside the `<body>` tag toward the bottom. With Gatsby you don't
|
||||
have direct access to the outer HTML document without copying it out of the
|
||||
cache.
|
||||
|
||||
And you don't need to copy it out of the cache. Gatsby offers an SSR
|
||||
(server-side rendering) API for rendering content into various parts of the
|
||||
document. Here is how we can use the
|
||||
[`onRenderBody`](https://www.gatsbyjs.org/docs/ssr-apis/#onRenderBody) callback
|
||||
to add a `<script>` tag to the end of the body.
|
||||
|
||||
```javascript
|
||||
// gatsby-ssr.js
|
||||
import React from "react"
|
||||
|
||||
export const onRenderBody = ({ setPostBodyComponents }) => {
|
||||
return setPostBodyComponents([
|
||||
<script src="https://some-3rd-party-script.js"></script>,
|
||||
])
|
||||
}
|
||||
```
|
||||
|
||||
`onRenderBody` provides several functions including `setPostBodyComponents`.
|
||||
This takes an array of React fragments that will be injected at the bottom of
|
||||
the document body.
|
||||
|
||||
[source](https://github.com/gaearon/overreacted.io/pull/55/files)
|
||||
Reference in New Issue
Block a user