JavaScript与jQuery入口函数

215 阅读1分钟

整理各入口函数写法及其注解:
入口函数的作用是等 DOM 结构(或者及图片,css等所有资源)渲染加载完毕就可以执行函数内的代码了。

<script>
    //1.# JavaScript原生的入口函数 方法一 等页面内容全部加在完毕,包含dom元素,图片,flash,css等才会执行函数
    window.onload = function() {
        alert('hello world')
    };
    //2.# JavaScript原生的入口函数 方法二 等dom元素全部加在完毕,就会执行函数,如果要获取图片尺寸,一般用onload
    document.addEventListener('DOMContentLoaded', function() {
        alert('hello world')
    });
    //3.jquery的入口函数 方法一 等dom元素全部加在完毕,就会执行函数(推荐),其相当于原生 JS 中的 DOMContentLoaded
    $(function() {
        alert('hello world')
    });
    //4.jquery的入口函数 方法二 等dom元素全部加在完毕,就会执行函数
    $(document).ready(function() {
        alert('hello world')
    });
    //5.jquery的入口函数 方法三 等页面内容全部加在完毕,包含dom元素,图片,flash,css等才会执行函数
    $(window).ready(function() {
        alert('hello world')
    })
</script>
  1. js文件可以不写入口函数,但是这样有些文件或元素尚未加载完成就操作dom元素会导致javaScript失效
  2. 可以将defer写入header头部的script标签,代表等DOM元素去全部加载完后,再执行js内容,这样就不用把script标签写在body底部了。
  3. heder中引入script加上type='module'标签,表示可以在js中使用import语法