在页面之间导航时显示加载程序 - PWA

Showing loader while navigating between pages - PWA

我有一个基于 PHP 的网站。

我已使用 service-workersmanifest.json 将网站转换为 PWA

现在,当我从主屏幕启动 PWA 时,它可以像应用程序一样正常工作。但是,问题是由于 PWA 不显示浏览器地址栏,用户无法知道页面正在重新加载或下一页正在加载。 当他们单击某些内容时,下一页会加载但未显示加载指示器

所以,现在我需要在页面之间导航时添加加载动画。由于所有页面都在不同的 URL 并且它们不是主框架。

我想不出一些解决办法。

理论

您需要做的是在页面生命周期中的两次显示加载动画:启动时关闭前.如果这样做,第一页的关闭动画会将用户带到第二页的开始动画,并且用户会收到应用程序的状态通知。

练习

1) 开始动画

我认为 jQuery 的 document.ready 事件是让用户与页面交互的好时机。所以当页面加载时加载动画将是active/shown。一旦页面加载完毕并准备好进行用户交互,您将结束动画。

The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins.

2)结束动画

为此,我使用浏览器的 onbeforeunload 事件。

The beforeunload event is fired when the window, the document and its resources are about to be unloaded.

onbeforeunload 在用户单击 link 或以其他方式触发导航过程时自动触发。所以只要听那个,你就可以开始你的结束动画了。

然后结束动画将在用户触发导航时开始,并在下一页的开始动画中受到欢迎。所以会有从用户点击开始到下一页加载结束的过渡。就像应用程序一样。

代码

这是我通常使用的代码片段;

$(function () {
    // page is loaded, it is safe to hide loading animation
    $('#loading-bg').hide();
    $('#loading-image').hide();

    $(window).on('beforeunload', function () {
        // user has triggered a navigation, show the loading animation
        $('#loading-bg').show();
        $('#loading-image').show();
    });
});

Here's a fiddle also with complete styles and HTML

希望对您有所帮助。