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) {
      var startLoad = new Date();
      // Service workers are supported. Use them.
      window.addEventListener('load', function () {
        var cleanServiceWorkerVersion = getCleanVersion(serviceWorkerVersion);
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + cleanServiceWorkerVersion;
        navigator.serviceWorker.register(serviceWorkerUrl) if ('serviceWorker' in navigator) {
          .then((reg) => { var startLoad = new Date();
            function waitForActivation(serviceWorker) { // Service workers are supported. Use them.
              serviceWorker.addEventListener('statechange', () => { window.addEventListener('load', function () {
                if (serviceWorker.state == 'activated') { var cleanServiceWorkerVersion = getCleanVersion(serviceWorkerVersion);
                  console.log('Installed new service worker.'); var serviceWorkerUrl = 'flutter_service_worker.js?v=' + cleanServiceWorkerVersion;
                  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; navigator.serviceWorker.register(serviceWorkerUrl)
            console.log('Active Service Worker URL: ' + (reg.active ? reg.active.scriptURL : 'None')); .then((reg) => {
            console.log('Latest Service Worker Version: ' + cleanServiceWorkerVersion); function waitForActivation(serviceWorker, isFirstTimeInstall) {
            console.log('Active Service Worker Version: ' + (currentSWVersion || 'None')); serviceWorker.addEventListener('statechange', () => {
            const isMatch = currentSWVersion === cleanServiceWorkerVersion; if (serviceWorker.state == 'activated') {
            console.log('Latest Service Worker Installed: ' + isMatch); console.log('Installed new service worker.');
loadMainDartJs();
// Only prompt if this is NOT the first time installing (i.e., returning user)
if (!isFirstTimeInstall && navigator.serviceWorker.controller) {
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();
}
} else if (isFirstTimeInstall) {
console.log('First time install - skipping reload prompt.');
}
}
});
}
const currentSWVersion = reg.active ? reg.active.scriptURL.split("=")[1].replaceAll("%22", "") : null;
console.log('Active Service Worker URL: ' + (reg.active ? reg.active.scriptURL : 'None'));
console.log('Latest Service Worker Version: ' + cleanServiceWorkerVersion);
console.log('Active Service Worker Version: ' + (currentSWVersion || 'None'));
const isMatch = currentSWVersion === cleanServiceWorkerVersion;
console.log('Latest Service Worker Installed: ' + isMatch);
            if (!reg.active && (reg.installing || reg.waiting)) { if (!reg.active && (reg.installing || reg.waiting)) {
              // First time load: wait for activation. // First time load: wait for activation but don't prompt.
              console.log('No Service Worker Available - Installing New Service Worker.'); console.log('No Service Worker Available - Installing New Service Worker.');
              waitForActivation(reg.installing || reg.waiting); waitForActivation(reg.installing || reg.waiting, true); // true = first time install
            } else if (!isMatch) { } else if (!isMatch) {
              // New version available: force update. // New version available: force update (returning user).
              console.log('New service worker available. Updating and waiting for activation.'); console.log('New service worker available. Updating and waiting for activation.');
              reg.update(); reg.update();
              waitForActivation(reg.installing); waitForActivation(reg.installing, false); // false = not first time
            } else { } else {
              // Existing service worker is still good. // Existing service worker is still good.
              console.log('Service Worker up-to-date, Loading app.'); console.log('Service Worker up-to-date, Loading app.');
              loadMainDartJs(); 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>