@@ -68,21 +68,15 @@ async function loadPage(url) {
6868 const parser = new DOMParser ( ) ;
6969 const doc = parser . parseFromString ( html , 'text/html' ) ;
7070
71- // Extract module script sources (they'll be loaded later by the router)
71+ // Extract module script sources
7272 const moduleScripts = componentLoader . extractModuleScriptSources ( doc ) ;
7373 console . log ( 'Extracted module scripts in router.js:' , moduleScripts ) ;
7474
7575 // Execute any inline scripts
7676 await componentLoader . executeInlineScripts ( doc ) ;
7777
78- // We want to keep script tags, so we'll use DOM methods to clone the content
79- // Create a fragment to hold the content
80- const contentFragment = document . createDocumentFragment ( ) ;
81-
82- // Clone all children from the body, including script tags
83- Array . from ( doc . body . children ) . forEach ( child => {
84- contentFragment . appendChild ( child . cloneNode ( true ) ) ;
85- } ) ;
78+ // Use the component loader to create a fragment with properly handled scripts
79+ const contentFragment = componentLoader . createFragmentWithScripts ( doc ) ;
8680
8781 // Create a wrapper for translation
8882 const wrapper = document . createElement ( 'div' ) ;
@@ -97,6 +91,40 @@ async function loadPage(url) {
9791 translatedFragment . appendChild ( wrapper . firstChild ) ;
9892 }
9993
94+ // Extract and clone script tags again to ensure they're executed
95+ const scriptElements = componentLoader . extractAndCloneScripts ( doc ) ;
96+
97+ // Add the script elements to the fragment
98+ scriptElements . forEach ( script => {
99+ translatedFragment . appendChild ( script ) ;
100+ } ) ;
101+
102+ // Create and add module scripts to the fragment
103+ if ( moduleScripts && moduleScripts . length > 0 ) {
104+ console . log ( `Adding ${ moduleScripts . length } module scripts to the fragment` ) ;
105+
106+ moduleScripts . forEach ( src => {
107+ // Create a new script element
108+ const script = document . createElement ( 'script' ) ;
109+ script . type = 'module' ;
110+
111+ // Convert to absolute URL if needed
112+ if ( src . startsWith ( 'http://' ) || src . startsWith ( 'https://' ) ) {
113+ script . src = src ;
114+ } else {
115+ // For local scripts, create absolute URL based on current origin
116+ const baseUrl = window . location . origin ;
117+ const absoluteSrc = src . startsWith ( '/' )
118+ ? `${ baseUrl } ${ src } `
119+ : `${ baseUrl } /${ src } ` ;
120+ script . src = absoluteSrc ;
121+ }
122+
123+ console . log ( `Adding module script: ${ script . src } ` ) ;
124+ translatedFragment . appendChild ( script ) ;
125+ } ) ;
126+ }
127+
100128 // Return the content wrapped in the default layout as a DOM fragment
101129 return createLayoutFragment ( translatedFragment ) ;
102130 } catch ( error ) {
0 commit comments