Skip to content

Commit

Permalink
fix: avoid inserting scripts when manual mode and not used
Browse files Browse the repository at this point in the history
Fixes #56
  • Loading branch information
harlan-zw committed Sep 2, 2024
1 parent 748af95 commit 0390a2b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
15 changes: 15 additions & 0 deletions .playground/pages/manual-off.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script lang="ts" setup>
import { defineRouteRules } from '#imports'
defineRouteRules({
delayHydration: 'manual',
})
</script>

<template>
<div>
<div>
<HydrationStatus />
</div>
</div>
</template>
6 changes: 4 additions & 2 deletions src/runtime/components/DelayHydration.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { defineAsyncComponent } from 'vue'
import { Comment, Fragment, defineAsyncComponent, h } from 'vue'

export default defineAsyncComponent({
loader() {
const hydrationApi = import.meta.client ? window._$delayHydration || Promise.resolve() : Promise.resolve()
return new Promise((resolve) => {
hydrationApi.then(() => {
resolve((props, { slots }) => slots.default?.(props))
resolve((props, { slots }) => {
return h(Fragment, [h(Comment, 'nuxt-delay-hydration-component'), slots.default?.(props)])
})
})
})
},
Expand Down
7 changes: 7 additions & 0 deletions src/runtime/nitro-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ export default defineNitroPlugin((nitro) => {
if (!currentMode)
return

if (currentMode === 'manual') {
// we only insert the script if the page is using it
if (!htmlContext.body.some(h => h.includes('<!--[--><!--nuxt-delay-hydration-component--><!--[-->'))) {
return
}
}

let extraScripts = ''
if (currentMode === 'init') {
const ASSET_RE = new RegExp(`<script[^>]*src="${config.app.buildAssetsDir}[^>]+><\\/script>`)
Expand Down

0 comments on commit 0390a2b

Please sign in to comment.