From 7fd6762c1657842de4404c5b2621154bf3b27218 Mon Sep 17 00:00:00 2001 From: Andrii Chubatiuk Date: Sat, 13 Sep 2025 19:36:39 +0300 Subject: [PATCH] transform/livereloadinject: Skip livereload.js injection if no tags found (note) This change is mainly motivated to support sites built by HTML fragments with e.g. a JS framework. Now we don't inject the script if we don't find any of `doctype` (the only one required by the HTML 5 spec), `html` or `head`. Co-authored-by: bep --- testscripts/commands/server.txt | 1 + transform/livereloadinject/livereloadinject.go | 9 +++++++++ transform/livereloadinject/livereloadinject_test.go | 8 ++++---- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/testscripts/commands/server.txt b/testscripts/commands/server.txt index 7f6afd8fd..5b2a2544d 100644 --- a/testscripts/commands/server.txt +++ b/testscripts/commands/server.txt @@ -24,6 +24,7 @@ myenv = "theproduction" -- config/development/params.toml -- myenv = "thedevelopment" -- layouts/index.html -- + Title: {{ .Title }}|BaseURL: {{ site.BaseURL }}|ServerPort: {{ site.ServerPort }}|myenv: {{ .Site.Params.myenv }}|Env: {{ hugo.Environment }}|IsServer: {{ hugo.IsServer }}| diff --git a/transform/livereloadinject/livereloadinject.go b/transform/livereloadinject/livereloadinject.go index 425d268b3..55e69f912 100644 --- a/transform/livereloadinject/livereloadinject.go +++ b/transform/livereloadinject/livereloadinject.go @@ -49,6 +49,15 @@ func New(baseURL *url.URL) transform.Transformer { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } + if idx == 0 { + // doctype is required for HTML5, we did not find it, + // and neither did we find html or head tags, so + // skip injection. + // This allows us to render partial HTML documents to be used in + // e.g. JS frameworks. + ft.To().Write(b) + return nil + } path := strings.TrimSuffix(baseURL.Path, "/") diff --git a/transform/livereloadinject/livereloadinject_test.go b/transform/livereloadinject/livereloadinject_test.go index d406b9c4d..5475fc5b6 100644 --- a/transform/livereloadinject/livereloadinject_test.go +++ b/transform/livereloadinject/livereloadinject_test.go @@ -59,12 +59,12 @@ func TestLiveReloadInject(t *testing.T) { c.Assert(apply("after"), qt.Equals, ""+expectBase+"after") }) - c.Run("Inject before other elements if all else omitted", func(c *qt.C) { - c.Assert(apply("after"), qt.Equals, expectBase+"after") + c.Run("Inject nothing if no doctype, html or head found", func(c *qt.C) { + c.Assert(apply("after"), qt.Equals, "after") }) - c.Run("Inject before text content if all else omitted", func(c *qt.C) { - c.Assert(apply("after"), qt.Equals, expectBase+"after") + c.Run("Inject nothing if no tag found", func(c *qt.C) { + c.Assert(apply("after"), qt.Equals, "after") }) c.Run("Inject after HeAd tag MiXed CaSe", func(c *qt.C) { -- 2.39.5