How to use Code Injection
Code Injection is a powerful, convenient tool to add CSS, JS, and more to your Ghost site. Learn how to get the most out of it in this tutorial.
Code Injection offers an interface for easily adding analytics, styles, custom fonts, meta tags, and scripts to a Ghost site. It's also the perfect tool for making minor edits to your theme or adding some cool effects with JavaScript. In this tutorial, learn how as well as everything you need to know about using Code Injection in Ghost.
What's Code Injection?
As the name hints, Code Injection injects code into your Ghost site. Access Code Injection from Settings →
On the Code Injection page, there are two areas: Site Header and Site Footer. Ghost injects any text entered into these boxes onto every page of your site.
Site Header code is injected into the <head>
tag. Site Footer code is injected before the closing </body>
tag. Both are added after other styles and scripts used by your theme.
<html>
<head>
<title>Page Title</title>
<!-- Code Injection Site Header added here -->
</head>
<body>
<!-- Your beautiful content -->
<!-- Code Injection Site Footer added here -->
</body>
</html>
Add CSS to the Site Header
One of the most common use cases for Code Injection is to add CSS to your Ghost site to customize the look and feel of your theme.
Let's say we had a site about animals using the Casper theme.
Everything's looking pretty good, but let's add some fun by using a custom typeface from Google Fonts. Find the font you want to use – for our animals site, we're going to use a font called "Luckiest Guy." Go to the typeface's page and click Get font.
Then, click Get embed code.
Copy the <link>
tags and paste them into the Site Header.
Next, add the CSS rules. Whenever you add CSS rules to the Site Header, wrap them in a <style>
tag. We only want our wacky new font to affect our headings, so we'll only apply it to them. And, since this font only has a single weight, we'll specify that, too.
That's it! The Code Injection is ready to be saved.
And so is our animals site – but now with a funky new font 💅
Add JS to the Site Footer
The second most common use case for Code Injection is to add JavaScript to a Ghost site. When adding JS, add it to the Site Footer so that it loads properly.
As an example, let's add a typewriter effect to our animals site. To help us along, we'll use the open-source TypewriterJS library.
Load the main script into the Site Footer.
Next, configure the TypewriterJS script and start it on the page. Whenever you add JS via Code Injection, wrap it in a <script>
tag.
All set! The Site Footer is ready to be saved.
And our animals site just got a little wilder 🦁
Summary
Code Injection is a powerful and convenient tool for quickly adding CSS, JS, and more to your Ghost site.
Many of Ghost's best Integrations rely on Code Injection – and now that you're an expert with it – you're more than ready to add one to your publication.