web load v2

This commit is contained in:
2025-11-14 12:47:15 +02:00
parent 47ca6d7311
commit 1f73aa3b87

View File

@@ -363,111 +363,110 @@
</script> </script>
<script defer=""> <script defer="">
    var serviceWorkerVersion = '{{flutter_service_worker_version}}';     var serviceWorkerVersion = '{{flutter_service_worker_version}}';
    var scriptLoaded = false; var scriptLoaded = false;
    function loadMainDartJs() { function loadMainDartJs() {
      console.log('Loading app...'); console.log('Loading app...');
      if (scriptLoaded) { if (scriptLoaded) {
        return; return;
      } }
      scriptLoaded = true; scriptLoaded = true;
      {{flutter_js}} {{flutter_js}}
      {{flutter_build_config}} {{flutter_build_config}}
      _flutter.loader.load({ _flutter.loader.load({
        serviceWorker: { serviceWorker: {
          serviceWorkerVersion: serviceWorkerVersion, serviceWorkerVersion: serviceWorkerVersion,
        }, },
        onEntrypointLoaded: function (engineInitializer) { onEntrypointLoaded: function (engineInitializer) {
          engineInitializer.initializeEngine().then(function (appRunner) { engineInitializer.initializeEngine().then(function (appRunner) {
            appRunner.runApp(); appRunner.runApp();
          }); });
        } }
      }); });
    } }
    // Helper function to strip quotes from the version placeholder // Helper function to strip quotes from the version placeholder
    function getCleanVersion(version) { function getCleanVersion(version) {
      return version.replace(/"/g, ''); return version.replace(/"/g, '');
    } }
    if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
      var startLoad = new Date(); var startLoad = new Date();
      // Service workers are supported. Use them. // Service workers are supported. Use them.
      window.addEventListener('load', function () { window.addEventListener('load', function () {
        var cleanServiceWorkerVersion = getCleanVersion(serviceWorkerVersion); var cleanServiceWorkerVersion = getCleanVersion(serviceWorkerVersion);
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + cleanServiceWorkerVersion; var serviceWorkerUrl = 'flutter_service_worker.js?v=' + cleanServiceWorkerVersion;
        navigator.serviceWorker.register(serviceWorkerUrl) navigator.serviceWorker.register(serviceWorkerUrl)
          .then((reg) => { .then((reg) => {
            function waitForActivation(serviceWorker) { function waitForActivation(serviceWorker, isFirstTimeInstall) {
              serviceWorker.addEventListener('statechange', () => { serviceWorker.addEventListener('statechange', () => {
                if (serviceWorker.state == 'activated') { if (serviceWorker.state == 'activated') {
                  console.log('Installed new service worker.'); console.log('Installed new service worker.');
                  loadMainDartJs(); loadMainDartJs();
                  // Optional: Prompt user to reload for the new version to take effect
                  // The user is currently running the OLD cached version of the app.
                  // This prompt is generally preferred over the previous logic.
                  if (navigator.serviceWorker.controller) {
                    // Only prompt if this isn't the first time loading.
                    console.log('New app version activated. Prompting for reload.');
                    // You can replace this confirm with a better UI notification.
                    if (confirm('A new version of the app is available. Refresh now to update?')) {
                      window.location.reload();
                    }
                  }
                }
              });
            }
            const currentSWVersion = reg.active ? reg.active.scriptURL.split("=")[1].replaceAll("%22", "") : null; // Only prompt if this is NOT the first time installing (i.e., returning user)
            console.log('Active Service Worker URL: ' + (reg.active ? reg.active.scriptURL : 'None')); if (!isFirstTimeInstall && navigator.serviceWorker.controller) {
            console.log('Latest Service Worker Version: ' + cleanServiceWorkerVersion); console.log('New app version activated. Prompting for reload.');
            console.log('Active Service Worker Version: ' + (currentSWVersion || 'None')); // You can replace this confirm with a better UI notification.
            const isMatch = currentSWVersion === cleanServiceWorkerVersion; if (confirm('A new version of the app is available. Refresh now to update?')) {
            console.log('Latest Service Worker Installed: ' + isMatch); window.location.reload();
}
} else if (isFirstTimeInstall) {
console.log('First time install - skipping reload prompt.');
}
}
});
}
            if (!reg.active && (reg.installing || reg.waiting)) { const currentSWVersion = reg.active ? reg.active.scriptURL.split("=")[1].replaceAll("%22", "") : null;
              // First time load: wait for activation. console.log('Active Service Worker URL: ' + (reg.active ? reg.active.scriptURL : 'None'));
              console.log('No Service Worker Available - Installing New Service Worker.'); console.log('Latest Service Worker Version: ' + cleanServiceWorkerVersion);
              waitForActivation(reg.installing || reg.waiting); console.log('Active Service Worker Version: ' + (currentSWVersion || 'None'));
            } else if (!isMatch) { const isMatch = currentSWVersion === cleanServiceWorkerVersion;
              // New version available: force update. console.log('Latest Service Worker Installed: ' + isMatch);
              console.log('New service worker available. Updating and waiting for activation.');
              reg.update(); if (!reg.active && (reg.installing || reg.waiting)) {
              waitForActivation(reg.installing); // First time load: wait for activation but don't prompt.
            } else { console.log('No Service Worker Available - Installing New Service Worker.');
              // Existing service worker is still good. waitForActivation(reg.installing || reg.waiting, true); // true = first time install
              console.log('Service Worker up-to-date, Loading app.'); } else if (!isMatch) {
              loadMainDartJs(); // New version available: force update (returning user).
            } console.log('New service worker available. Updating and waiting for activation.');
          }) reg.update();
waitForActivation(reg.installing, false); // false = not first time
} else {
// Existing service worker is still good.
console.log('Service Worker up-to-date, Loading app.');
loadMainDartJs();
}
})
.catch((error) => { .catch((error) => {
console.error('Service Worker registration failed:', error); console.error('Service Worker registration failed:', error);
loadMainDartJs(); // Fallback if registration fails completely loadMainDartJs(); // Fallback if registration fails completely
}); });
        // If service worker doesn't succeed in a reasonable amount of time, // If service worker doesn't succeed in a reasonable amount of time,
        // fallback to plain <script> tag. // fallback to plain <script> tag.
        setTimeout(() => { setTimeout(() => {
          if (!scriptLoaded) { if (!scriptLoaded) {
            console.warn( console.warn(
              'Failed to load app from a service worker. Falling back to plain <script> tag.', 'Failed to load app from a service worker. Falling back to plain <script> tag.',
            ); );
            loadMainDartJs(); loadMainDartJs();
          } }
        }, 500); }, 500);
        var finishLoad = new Date(); var finishLoad = new Date();
        var loadTime = (finishLoad.getTime() - startLoad.getTime()); var loadTime = (finishLoad.getTime() - startLoad.getTime());
        console.log("Load Time: " + loadTime); console.log("Load Time: " + loadTime);
      }); });
    } }
    else { else {
      // Service workers not supported. Just drop the <script> tag. // Service workers not supported. Just drop the <script> tag.
      console.log('Service Workers Not Supported. Loading app directly.'); console.log('Service Workers Not Supported. Loading app directly.');
      loadMainDartJs(); loadMainDartJs();
    } }
  </script>   </script>