main.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // 使用 IIFE 包裹以避免全局变量污染
  2. (function () {
  3. var loadingBar = document.querySelector(".loading-bar");
  4. var progress = document.querySelector(".loading-bar .progress");
  5. var timer = null;
  6. let pjax;
  7. function initAni() {
  8. loadingBar = document.querySelector(".loading-bar");
  9. progress = document.querySelector(".loading-bar .progress");
  10. }
  11. // 初始化 PJAX
  12. function initPjax() {
  13. try {
  14. const Pjax = window.Pjax || function () { };
  15. pjax = new Pjax({
  16. selectors: [
  17. "head meta",
  18. "head title",
  19. "body container",
  20. ".pjax-reload"
  21. ],
  22. currentUrlFullReload: true
  23. });
  24. } catch (e) {
  25. console.log('PJAX 初始化出错:' + e);
  26. }
  27. }
  28. function endLoad() {
  29. clearInterval(timer);
  30. progress.style.width = "100%";
  31. loadingBar.classList.remove("loading");
  32. setTimeout(function () {
  33. progress.style.width = 0;
  34. }, 400);
  35. }
  36. // 初始化
  37. function initialize() {
  38. initPjax();
  39. initAni();
  40. }
  41. // 触发器
  42. // 网页加载完毕后触发
  43. window.addEventListener('DOMContentLoaded', () => initialize());
  44. // Pjax 开始时执行的函数
  45. document.addEventListener("pjax:send", function () {
  46. var loadingBarWidth = 20;
  47. var MAX_LOADING_WIDTH = 95;
  48. loadingBar.classList.add("loading");
  49. progress.style.width = loadingBarWidth + "%";
  50. clearInterval(timer);
  51. timer = setInterval(function () {
  52. loadingBarWidth += 3;
  53. if (loadingBarWidth > MAX_LOADING_WIDTH) {
  54. loadingBarWidth = MAX_LOADING_WIDTH;
  55. }
  56. progress.style.width = loadingBarWidth + "%";
  57. }, 500);
  58. });
  59. // 监听 Pjax 完成后,重新加载
  60. document.addEventListener("pjax:complete", function () {
  61. endLoad();
  62. });
  63. })();