- Stable
2.0.1
Toggle Menu
Eleventy
1.93s
Next.js
70.65s
Quick Tip: Inline Minified JavaScript
Originally posted on The Simplest Web Site That Could Possible Work Well on zachleat.com
This tip works great if you have small JS utilities that you’d like to have in your <head>
. For example, this works great with the Filament Group loadJS
or loadCSS
utilities.
Installation
npm install terser
to make the terser minifier available in your project.
Configuration
Add the following jsmin
filter to your Eleventy Config file:
eleventy.config.js
import { minify } from "terser";
export default function (eleventyConfig) {
eleventyConfig.addFilter("jsmin", async function (code, callback) {
try {
const minified = await minify(code);
callback(null, minified.code);
} catch (err) {
console.error("Terser error: ", err);
// Fail gracefully.
callback(null, code);
}
});
};
const { minify } = require("terser");
module.exports = function (eleventyConfig) {
eleventyConfig.addFilter("jsmin", async function (code, callback) {
try {
const minified = await minify(code);
callback(null, minified.code);
} catch (err) {
console.error("Terser error: ", err);
// Fail gracefully.
callback(null, code);
}
});
};
Create your JavaScript File
Add a sample JavaScript file to your _includes
directory. Let’s call it sample.js
.
// Hi
console.log("Hi");
Capture and Minify
Capture the JavaScript into a variable and run it through the filter (this sample is using Nunjucks syntax)
<!-- capture the JS content as a Nunjucks variable -->
{% set js %} {% include "sample.js" %} {% endset %}
<!-- feed it through our jsmin filter to minify -->
<script>
{{ js | jsmin | safe }}
</script>
Warning about Content Security Policy
WARNING:
If you are using a Content Security Policy on your website, make sure the
script-src
directive allows 'unsafe-inline'
. Otherwise, your inline Javascript will not load.
All Quick Tips
- Quick Tip: Inline Minified CSS
- Quick Tip: Add Edit on GitHub Links to All Pages
- Quick Tip: Inline Minified JavaScript
- Quick Tip: Zero Maintenance Tag Pages for your Blog
- Quick Tip: Super Simple CSS Concatenation
- Quick Tip: Adding a 404 Not Found Page to your Static Site
- Quick Tip: Fetch GitHub Stargazers Count (and More) at Build Time
- Quick Tip: Trigger a Netlify Build Every Day
- Quick Tip: Cache Data Requests
- Quick Tip: Transform Global Data using an `eleventyComputed.js` Global Data File
- Quick Tip: Use local plugins to reduce config file size
- Quick Tip: Draft Posts using Computed Data
- View all of the Eleventy Quick Tips.