diff --git a/config/static_caching.php b/config/static_caching.php index 2cb9f69f8f4..e190b9729d6 100644 --- a/config/static_caching.php +++ b/config/static_caching.php @@ -125,6 +125,8 @@ 'nocache' => 'cache', + 'nocache_js_position' => 'body', + /* |-------------------------------------------------------------------------- | Replacers diff --git a/src/StaticCaching/Replacers/NoCacheReplacer.php b/src/StaticCaching/Replacers/NoCacheReplacer.php index c1531990058..5faaecc1273 100644 --- a/src/StaticCaching/Replacers/NoCacheReplacer.php +++ b/src/StaticCaching/Replacers/NoCacheReplacer.php @@ -79,19 +79,40 @@ private function modifyFullMeasureResponse(Response $response) $contents = $response->getContent(); if ($cacher->shouldOutputJs()) { - $insertBefore = collect([ - Str::position($contents, ''), - ])->filter()->min(); - - $js = ""; - - $contents = Str::substrReplace($contents, $js, $insertBefore, 0); + $contents = match ($pos = $this->insertPosition()) { + 'head' => $this->insertJsInHead($contents, $cacher), + 'body' => $this->insertJsInBody($contents, $cacher), + default => throw new \Exception('Invalid nocache js insert position ['.$pos.']'), + }; } $contents = str_replace('NOCACHE_PLACEHOLDER', $cacher->getNocachePlaceholder(), $contents); $response->setContent($contents); } + + private function insertPosition() + { + return config('statamic.static_caching.nocache_js_position', 'body'); + } + + private function insertJsInHead($contents, $cacher) + { + $insertBefore = collect([ + Str::position($contents, ''), + ])->filter()->min(); + + $js = ""; + + return Str::substrReplace($contents, $js, $insertBefore, 0); + } + + private function insertJsInBody($contents, $cacher) + { + $js = $cacher->getNocacheJs(); + + return str_replace('
{{ template_content }}', '', $contents); + } } diff --git a/tests/StaticCaching/FullMeasureStaticCachingTest.php b/tests/StaticCaching/FullMeasureStaticCachingTest.php index 447b4c87de6..ed31ae1425d 100644 --- a/tests/StaticCaching/FullMeasureStaticCachingTest.php +++ b/tests/StaticCaching/FullMeasureStaticCachingTest.php @@ -58,7 +58,7 @@ public function index() })::register(); $this->withFakeViews(); - $this->viewShouldReturnRaw('layout', '