window.onload是内置的JavaScript事件,但由于它的实现在浏览器(Firefox、Internet Explorer 6、Internet Explorer 8和Opera)上有微妙个怪癖,jQuery提供了document.ready,它将这些怪癖抽象出来,并在页面的DOM准备好后立即触发(不等待图像等)。
$(document).ready(function() {
// Executes when the HTML document is loaded and the DOM is readyalert("Document is ready");});
// .load() method deprecated from jQuery 1.8 onward$(window).on("load", function() {
// Executes when complete page is fully loaded, including// all frames, objects and imagesalert("Window is loaded");});
// document ready events$(document).ready(function(){alert("document is ready..");})
// using JQuery$(function(){alert("document is ready..");})
// window on load eventfunction myFunction(){alert("window is loaded..");}window.onload = myFunction;
jQuery.ready.promise = function( obj ) {if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.// we once tried to use readyState "interactive" here, but it caused issues like the one// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15if ( document.readyState === "complete" ) {// Handle it asynchronously to allow scripts the opportunity to delay readysetTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded} else if ( document.addEventListener ) {// Use the handy event callbackdocument.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always workwindow.addEventListener( "load", completed, false );
// If IE event model is used} else {// Ensure firing before onload, maybe late but safe also for iframesdocument.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always workwindow.attachEvent( "onload", completed );
// If IE and not a frame// continually check to see if the document is readyvar top = false;
try {top = window.frameElement == null && document.documentElement;} catch(e) {}
if ( top && top.doScroll ) {(function doScrollCheck() {if ( !jQuery.isReady ) {
try {// Use the trick by Diego Perini// http://javascript.nwbox.com/IEContentLoaded/top.doScroll("left");} catch(e) {return setTimeout( doScrollCheck, 50 );}
// detach all dom ready eventsdetach();
// and execute any waiting functionsjQuery.ready();}})();}}}return readyList.promise( obj );};jQuery.fn.ready = function( fn ) {// Add the callbackjQuery.ready.promise().done( fn );
return this;};
<script>// DOM hasn't been completely parseddocument.body; // null
window.addEventListener('DOMContentLoaded', () => {// Now safely manipulate DOMdocument.querySelector('#id');document.body.appendChild();});
/*** Should be used only to detect a fully-loaded page.** If you just want to manipulate DOM safely, `DOMContentLoaded` is better.*/window.addEventListener('load', () => {// Safely manipulate DOM toodocument.links;});</script>