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 <bjorn.erik.pedersen@gmail.com>
This commit is contained in:
Andrii Chubatiuk
2025-09-13 19:36:39 +03:00
committed by Bjørn Erik Pedersen
parent 584f052f39
commit 7fd6762c16
3 changed files with 14 additions and 4 deletions
@@ -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, "/")
@@ -59,12 +59,12 @@ func TestLiveReloadInject(t *testing.T) {
c.Assert(apply("<!doctype html>after"), qt.Equals, "<!doctype html>"+expectBase+"after")
})
c.Run("Inject before other elements if all else omitted", func(c *qt.C) {
c.Assert(apply("<title>after</title>"), qt.Equals, expectBase+"<title>after</title>")
c.Run("Inject nothing if no doctype, html or head found", func(c *qt.C) {
c.Assert(apply("<title>after</title>"), qt.Equals, "<title>after</title>")
})
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) {