Eleventy Live Reload for HTML5 Documents Without a <body> Tag
Every time a file is saved, Eleventy can automatically regenerate the site
and live reload it in a browser. The live reload is provided by Browsersync,
which searches for the document’s <body>
tag and adds a JavaScript
snippet immediately after it. The Eleventy documentation calls out:
Browsersync requires a
<body>
tag in your template for live-reload to work properly.
If live reload is not working, it might be because the document doesn’t contain
a <body>
tag and therefore Browsersync hasn’t appended its
JavaScript.
No <body>
? <DOCTYPE>
to the rescue
HTML5 doesn’t require a <body>
tag and the Google Style Guide
recommends omitting it. A valid HTML5 document will have a
<DOCTYPE>
tag, though.
We can configure Browsersync to add its JavaScript immediately after the
<DOCTYPE>
tag instead. Even better, we can set that configuration in
our .eleventy.js
file.
module.exports = function (eleventyConfig) {
eleventyConfig.setBrowserSyncConfig({
snippetOptions: {
// Insert BrowserSync’s JavaScript immediately after the DOCTYPE tag,
// instead of the <body> tag.
rule: {
match: /<!DOCTYPE html>/i,
fn: function (snippet, match) {
return snippet + match;
},
},
},
});
};