学习笔记——JavaScript预加载的疑问

110 阅读1分钟

01 用css和Javascript实现

<div class="box">
    <div id="preload1"></div>
    <div id="preload2"></div>
    <div id="preload3"></div>
    <div id="preload4"></div>
</div>
// 将加载图片封装到一个函数中
function preloader(){
    if(document.getElementById){                //5
        document.getElementById('preload1').style.background = 'url(./images/001.jpg) no-repeat -9999px -9999px'
        document.getElementById('preload2').style.background = 'url(./images/002.jpg) no-repeat -9999px -9999px'
        document.getElementById('preload3').style.background = 'url(./images/003.jpg) no-repeat -9999px -9999px'
        document.getElementById('preload4').style.background = 'url(./images/004.jpg) no-repeat -9999px -9999px'
    }
}
// 监听页面是否加载完成,只能加载完成后才执行预加载
function addLoadEvent(fn){
    var oldload = window.onload;             //1
    if(typeof oldload == 'function'){        //2
        window.onload = fn                   //3
    }else{
        window.onload = function(){          //4
        if(oldload){
            oldload()
            }
        fn();
        }}}
addLoadEvent(preloader)
1.oldload为什么是function类型,涉及到回调函数的知识吗?(还没学到,学了回调函数再回头填坑)

2.网上有些写的是!=,也有写==,应该是什么呢?

3.执行了onload=fn,onload又被调用了一次,那oldload是fc又有什么用?

4.这句和onload=fn有什么区别,感觉都是再掉了一次fn函数?里面还包装了一个if(oldload)又是有什么用呢?

5.这个document.getElementById是一个方法,为什么能这么写呢?

02 仅使用JavaScript实现预加载

// 预加载图片
function preloader(){
if(document.images){                                     //1
var img1 = new Image().src = './images/001.jpg';
var img2 = new Image().src = './images/002.jpg';
var img3 = new Image().src = './images/003.jpg';
var img4 = new Image().src = './images/004.jpg';
}}

1.这个document.images是什么?第一次见,同前一个问题5

03 使用Ajax实现预加载

onload = function(){
    var xhr1 = null, xhr2 = null, xhr3 = null;
    setTimeout(function(){
        // 实例化请求对象
        xhr1 = new XMLHttpRequest();
        // 创建请求
        xhr1.open('get','https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js',true);
        // 向后台发送请求
        xhr1.send();
        xhr2 = new XMLHttpRequest();
        xhr2.open('get','https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.css',true);
        xhr2.send();
        xhr3 = new XMLHttpRequest();
        xhr3.open('get','https://cdn.bootcdn.net/ajax/libs/vue/3.0.0-beta.20/vue.cjs.js',true);
        xhr3.send();
        
        xhr2.onreadystatechange = function(){
            if(xhr2.readyState == 4 && xhr2.status == 200){
                console.log(xhr2.responseText)
        }}
        xhr3.onreadystatechange = function(){
            console.log(xhr3.responseText)
        }
},1000)} // 使用定时器的目的:避免请求的时间过长

占时问不出来问题留个坑后面问