main.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. });
  23. } catch (e) {
  24. console.log('PJAX 初始化出错:' + e);
  25. }
  26. }
  27. function endLoad() {
  28. clearInterval(timer);
  29. progress.style.width = "100%";
  30. loadingBar.classList.remove("loading");
  31. setTimeout(function () {
  32. progress.style.width = 0;
  33. }, 400);
  34. }
  35. // 初始化
  36. function initialize() {
  37. initPjax();
  38. initAni();
  39. }
  40. // 触发器
  41. // 网页加载完毕后触发
  42. window.addEventListener('DOMContentLoaded', () => initialize());
  43. // Pjax 开始时执行的函数
  44. document.addEventListener("pjax:send", function () {
  45. var loadingBarWidth = 20;
  46. var MAX_LOADING_WIDTH = 95;
  47. loadingBar.classList.add("loading");
  48. progress.style.width = loadingBarWidth + "%";
  49. clearInterval(timer);
  50. timer = setInterval(function () {
  51. loadingBarWidth += 3;
  52. if (loadingBarWidth > MAX_LOADING_WIDTH) {
  53. loadingBarWidth = MAX_LOADING_WIDTH;
  54. }
  55. progress.style.width = loadingBarWidth + "%";
  56. }, 500);
  57. });
  58. // 监听 Pjax 完成后,重新加载
  59. document.addEventListener("pjax:complete", function () {
  60. endLoad();
  61. });
  62. })();