预加载器应该在 DOMContentLoaded 或 load event

时间:2021-01-21 15:45:18

标签: javascript html css

我想在我的网站上添加一个预加载器,直到网站完全加载图像、js、字体,但我很困惑我应该使用哪个

window.addEventListener('DOMContentLoaded', () => {
  // code
});

window.addEventListener('load', () => {
  // code
});

如果我使用了 load 或 DOMContentLoaded,我应该停止为我的脚本文件使用 defer 吗?

而且,如果我导入了模块,它是否应该在事件之外?例如:

import { gsap } from "gsap";
window.addEventListener('DOMContentLoaded', () => {
 // code
});

2 个答案:

答案 0 :(得分:0)

当您选择的事件被触发时,您可以隐藏预加载器。

延迟属性 此布尔属性设置为向浏览器指示该脚本将在解析文档之后但在触发 DOMContentLoaded 之前执行。

DOM 层次结构完全构建后,DOMContentLoaded 事件将触发,加载事件将在所有图像和子帧加载完成后执行。

您还可以阅读文档...

https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

答案 1 :(得分:0)

我将这个预加载器代码用于我的网站。你可以检查一下。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <div id="preloader" style="position: fixed; left: 0; top: 0; z-index: 999; width: 
  100%; height: 100%; overflow: visible; background: #333 url('pre_loading.gif') no- 
  repeat center center;"></div>

 <div id="container" style="display:none;">your page content here</div>
   <script>
    $(window).load(function(){
        $('#preloader').fadeOut('slow',function(){$(this).remove();});
        $('#container').show();
        
    });
  </script>
</body>
 
</html>
相关问题