main.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // main.js - 前端增强脚本
  2. document.addEventListener("DOMContentLoaded", function () {
  3. // 图片懒加载(浏览器原生支持,这里作为后备)
  4. if ("loading" in HTMLImageElement.prototype) {
  5. const images = document.querySelectorAll('img[loading="lazy"]');
  6. images.forEach((img) => {
  7. img.src = img.src; // 触发加载
  8. });
  9. } else {
  10. // 降级方案:使用 IntersectionObserver
  11. const lazyImages = document.querySelectorAll('img[loading="lazy"]');
  12. if ("IntersectionObserver" in window) {
  13. const observer = new IntersectionObserver((entries) => {
  14. entries.forEach((entry) => {
  15. if (entry.isIntersecting) {
  16. const img = entry.target;
  17. img.src = img.dataset.src || img.src;
  18. observer.unobserve(img);
  19. }
  20. });
  21. });
  22. lazyImages.forEach((img) => observer.observe(img));
  23. }
  24. }
  25. // 删除确认弹窗(已在模板中使用 confirm,这里作为补充)
  26. const deleteForms = document.querySelectorAll('form[action*="delete"]');
  27. deleteForms.forEach((form) => {
  28. form.addEventListener("submit", function (e) {
  29. if (!confirm("确定要删除吗?此操作不可恢复。")) {
  30. e.preventDefault();
  31. }
  32. });
  33. });
  34. });