window.onload 与 $(document).ready()

发布于 2024-09-19 19:13:30 字数 327 浏览 10 评论 0 原文

JavaScript 的 window.onload< 之间有什么区别/a> 和 jQuery 的 $(document).ready()方法?

What are the differences between JavaScript's window.onload and jQuery's $(document).ready() method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

原谅我要高飞 2024-09-26 19:13:30

ready 事件在 HTML 文档加载后发生,而 onload 事件稍后发生,此时所有内容(例如图像)也已加载。

onload 事件是 DOM 中的标准事件,而 ready 事件是 jQuery 特有的。 ready 事件的目的是它应该在文档加载后尽早发生,以便向页面中的元素添加功能的代码不必等待所有内容都加载完毕。加载。

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

戴着白色围巾的女孩 2024-09-26 19:13:30

window.onload 是内置 JavaScript 事件,但其实现在不同浏览器(Firefox、Internet Explorer 6、Internet Explorer 8 和Opera),jQuery 提供了 document.ready,它将它们抽象出来,并在页面的 DOM 准备好后立即触发(不等待图像等)。

$(document).ready (请注意,它不是 document.ready,它是未定义的)是一个 jQuery 函数,包装并提供 > 与以下事件的一致性:

  • DOMContentLoaded - 一个新的事件,在加载文档的 DOM 时触发(可能在图像等之前的某个时间)。已加载);同样,在 Internet Explorer 和世界其他地方
  • 以及 window.onload(甚至在旧浏览器中也实现)中略有不同,它在整个页面加载(图像、样式等)时触发。

window.onload is the built-in JavaScript event, but as its implementation had subtle quirks across browsers (Firefox, Internet Explorer 6, Internet Explorer 8, and Opera), jQuery provides document.ready, which abstracts those away, and fires as soon as the page's DOM is ready (doesn't wait for images, etc.).

$(document).ready (note that it's not document.ready, which is undefined) is a jQuery function, wrapping and providing consistency to the following events:

  • DOMContentLoaded - a newish event which fires when the document's DOM is loaded (which may be some time before the images, etc. are loaded); again, slightly different in Internet Explorer and in rest of the world
  • and window.onload (which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)
昔梦 2024-09-26 19:13:30

$(document).ready() 是一个 jQuery 事件。一旦 DOM 准备好(这意味着浏览器已经解析了 HTML 并构建了 DOM 树),JQuery 的 $(document).ready() 方法就会被调用。这允许您在文档准备好进行操作时立即运行代码。

例如,如果浏览器支持 DOMContentLoaded 事件(许多非 IE 浏览器也支持),那么它将触发该事件。 (请注意,DOMContentLoaded 事件仅在 IE9+ 中添加到 IE 中。)

为此可以使用两种语法:

$( document ).ready(function() {
   console.log( "ready!" );
});

或者简写版本:

$(function() {
   console.log( "ready!" );
});

$(document).ready() 的要点:

  • 它不会等待图像加载。
  • 用于在 DOM 完全加载时执行 JavaScript。将事件处理程序放在这里。
  • 可以多次使用。
  • 当您收到“$ 未定义”时,请将 $ 替换为 jQuery
  • 如果您想操作图像,则不使用。使用 $(window).load() 代替。

window.onload() 是一个原生 JavaScript 函数。当页面上的所有内容(包括 DOM(文档对象模型)、横幅广告和图像)加载完毕时,将触发 window.onload() 事件。两者之间的另一个区别是,虽然我们可以有多个 $(document).ready() 函数,但我们只能有一个 onload 函数。

$(document).ready() is a jQuery event. JQuery’s $(document).ready() method gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.

For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. (Note that the DOMContentLoaded event was only added to IE in IE9+.)

Two syntaxes can be used for this:

$( document ).ready(function() {
   console.log( "ready!" );
});

Or the shorthand version:

$(function() {
   console.log( "ready!" );
});

Main points for $(document).ready():

  • It will not wait for the images to be loaded.
  • Used to execute JavaScript when the DOM is completely loaded. Put event handlers here.
  • Can be used multiple times.
  • Replace $ with jQuery when you receive "$ is not defined."
  • Not used if you want to manipulate images. Use $(window).load() instead.

window.onload() is a native JavaScript function. The window.onload() event fires when all the content on your page has loaded, including the DOM (document object model), banner ads and images. Another difference between the two is that, while we can have more than one $(document).ready() function, we can only have one onload function.

煞人兵器 2024-09-26 19:13:30

一个小提示:

始终使用window.addEventListener向窗口添加事件。因为这样您就可以在不同的事件处理程序中执行代码。

正确代码:

window.addEventListener('load', function () {
  alert('Hello!')
})

window.addEventListener('load', function () {
  alert('Bye!')
})

代码无效:

window.onload = function () {
  alert('Hello!') // it will not work!!!
}

window.onload = function () {
  alert('Bye!') 
}

这是因为 onload 只是对象的属性,它被覆盖了。

类比addEventListener,最好使用$(document).ready()而不是onload。

A little tip:

Always use the window.addEventListener to add an event to window. Because that way you can execute the code in different event handlers .

Correct code:

window.addEventListener('load', function () {
  alert('Hello!')
})

window.addEventListener('load', function () {
  alert('Bye!')
})

Invalid code:

window.onload = function () {
  alert('Hello!') // it will not work!!!
}

window.onload = function () {
  alert('Bye!') 
}

This is because onload is just property of the object, which is overwritten.

By analogy with addEventListener, it is better to use $(document).ready() rather than onload.

做个ˇ局外人 2024-09-26 19:13:30

当页面上的所有内容(包括 DOM(文档对象模型)内容和异步 JavaScript框架和图像)完全加载时,将触发 Windows load 事件强>。您还可以使用 body onload=。两者是相同的; window.onload = function(){} 是使用同一事件的不同方式。

jQuery $document.ready 函数事件的执行时间比 window.onload 稍早,并且在 DOM(文档对象模型)加载后调用你的页面。它不会等待图像、帧完全加载

摘自以下文章:
如何$document.ready()window.onload() 不同

A Windows load event fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){} and <body onload="func();"> are different ways of using the same event.

jQuery $document.ready function event executes a bit earlier than window.onload and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.

Taken from the following article:
how $document.ready() is different from window.onload()

眼趣 2024-09-26 19:13:30
$(document).ready(function() {

    // Executes when the HTML document is loaded and the DOM is ready
    alert("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 images
     alert("Window is loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

$(document).ready(function() {

    // Executes when the HTML document is loaded and the DOM is ready
    alert("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 images
     alert("Window is loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

轮廓§ 2024-09-26 19:13:30

$(document).ready() 是一个 jQuery 事件,当 HTML 文档完全加载时发生,而 window.onload事件稍后发生,当加载页面上的所有内容(包括图像)时。

另外,window.onload 是 DOM 中的纯 JavaScript 事件,而 $(document).ready() 事件是 jQuery 中的方法。

$(document).ready() 通常是 jQuery 的包装器,以确保所有加载的元素都可以在 jQuery 中使用...

查看 jQuery 源代码以了解其工作原理:

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:15
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            setTimeout( jQuery.ready );

        // Standards-based browsers support DOMContentLoaded
        } else if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", completed, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", completed, false );

        // If IE event model is used
        } else {
            // Ensure firing before onload, maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", completed );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", completed );

            // If IE and not a frame
            // continually check to see if the document is ready
            var 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 events
                        detach();

                        // and execute any waiting functions
                        jQuery.ready();
                    }
                })();
            }
        }
    }
    return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

另外我创建了下图作为两者的快速参考:

在此处输入图像描述

The $(document).ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window.onload event occurs later, when everything including images on the page loaded.

Also window.onload is a pure javascript event in the DOM, while the $(document).ready() event is a method in jQuery.

$(document).ready() is usually the wrapper for jQuery to make sure the elements all loaded in to be used in jQuery...

Look at to jQuery source code to understand how it's working:

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:15
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            setTimeout( jQuery.ready );

        // Standards-based browsers support DOMContentLoaded
        } else if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", completed, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", completed, false );

        // If IE event model is used
        } else {
            // Ensure firing before onload, maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", completed );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", completed );

            // If IE and not a frame
            // continually check to see if the document is ready
            var 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 events
                        detach();

                        // and execute any waiting functions
                        jQuery.ready();
                    }
                })();
            }
        }
    }
    return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

Also I have created the image below as a quick references for both:

enter image description here

雄赳赳气昂昂 2024-09-26 19:13:30

在 Internet Explorer 中使用 $(document).ready() 时需要注意。如果 HTTP 请求在整个文档加载之前被中断(例如,当页面流式传输到浏览器时,单击另一个链接),IE 将触发 $(document).ready事件。

如果 $(document).ready() 事件中的任何代码引用 DOM 对象,则可能会找不到这些对象,并且可能会发生 JavaScript 错误。要么保护对这些对象的引用,要么将引用这些对象的代码推迟到 window.load 事件。

我无法在其他浏览器(特别是 Chrome 和 Firefox)中重现此问题

A word of caution on using $(document).ready() with Internet Explorer. If an HTTP request is interrupted before the entire document is loaded (for example, while a page is streaming to the browser, another link is clicked) IE will trigger the $(document).ready event.

If any code within the $(document).ready() event references DOM objects, the potential exists for those objects to be not found, and Javascript errors can occur. Either guard your references to those objects, or defer code which references those objects to the window.load event.

I have not been able to reproduce this problem in other browsers (specifically, Chrome and Firefox)

她如夕阳 2024-09-26 19:13:30

事件

$(document).on('ready', handler) 绑定到来自 jQuery 的就绪事件。 加载 DOM 时会调用该处理程序。 图像等资产可能仍然缺失。如果文档在绑定时已准备好,则永远不会调用它。 jQuery 使用 DOMContentLoaded - 事件,如果不可用则模拟它。

$(document).on('load', handler) 是一个事件,一旦从服务器加载所有资源,就会触发该事件。图像现已加载。虽然 onload 是原始 HTML 事件,但 ready 是由 jQuery 构建的。

函数

$(document).ready(handler) 实际上是一个 promise如果文档在调用时已准备好,处理程序将立即被调用。否则它将绑定到ready事件。

在 jQuery 1.8 之前,$(document).load(handler) 已存在作为 $(document).on('load',handler) 的别名。

进一步阅读

Events

$(document).on('ready', handler) binds to the ready event from jQuery. The handler is called when the DOM is loaded. Assets like images maybe still are missing. It will never be called if the document is ready at the time of binding. jQuery uses the DOMContentLoaded-Event for that, emulating it if not available.

$(document).on('load', handler) is an event that will be fired once all resources are loaded from the server. Images are loaded now. While onload is a raw HTML event, ready is built by jQuery.

Functions

$(document).ready(handler) actually is a promise. The handler will be called immediately if document is ready at the time of calling. Otherwise it binds to the ready-Event.

Before jQuery 1.8, $(document).load(handler) existed as an alias to $(document).on('load',handler).

Further Reading

国粹 2024-09-26 19:13:30

window.onload: 一个普通的 JavaScript 事件。

document.ready: 加载整个 HTML 时的特定 jQuery 事件。< /em>

window.onload: A normal JavaScript event.

document.ready: A specific jQuery event when the entire HTML has been loaded.

青丝拂面 2024-09-26 19:13:30

要记住的一件事(或者我应该说回忆)是,您不能像使用 ready 那样堆叠 onload。换句话说,jQuery magic 允许同一页面上有多个 ready,但你不能使用 onload 来做到这一点。

最后一个 onload 将推翻之前的任何 onload

处理这个问题的一个好方法是使用显然由 Simon Willison 编写的函数,并在 使用多个 JavaScript Onload 函数

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

// Example use:
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* More code to run on page load */
});

One thing to remember (or should I say recall) is that you cannot stack onloads like you can with ready. In other words, jQuery magic allows multiple readys on the same page, but you can't do that with onload.

The last onload will overrule any previous onloads.

A nice way to deal with that is with a function apparently written by one Simon Willison and described in Using Multiple JavaScript Onload Functions.

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

// Example use:
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* More code to run on page load */
});
七禾 2024-09-26 19:13:30

Document.ready(一个 jQuery 事件)会在所有元素就位时触发,并且可以在 JavaScript 代码中引用它们,但内容不一定会加载。 Document.ready 在 HTML 文档加载时执行。

$(document).ready(function() {

    // Code to be executed
    alert("Document is ready");
});

然而,window.load 将等待页面完全加载。这包括内部框架、图像等。

$(window).load(function() {

    //Fires when the page is loaded completely
    alert("window is loaded");
});

Document.ready (a jQuery event) will fire when all the elements are in place, and they can be referenced in the JavaScript code, but the content is not necessarily loaded. Document.ready executes when the HTML document is loaded.

$(document).ready(function() {

    // Code to be executed
    alert("Document is ready");
});

The window.load however will wait for the page to be fully loaded. This includes inner frames, images, etc.

$(window).load(function() {

    //Fires when the page is loaded completely
    alert("window is loaded");
});
忘你却要生生世世 2024-09-26 19:13:30

document.ready 事件在 HTML 文档加载后发生,而 window.onload 事件总是稍后在所有内容(图像等)加载后发生。

如果您想“尽早”干预渲染过程,而不需要等待图像加载,则可以使用 document.ready 事件。
如果您需要在脚本“执行某些操作”之前准备好图像(或任何其他“内容”),则需要等到 window.onload

例如,如果您正在实现“幻灯片放映”模式,并且需要根据图像大小执行计算,则可能需要等到 window.onload。否则,您可能会遇到一些随机问题,具体取决于图像加载的速度。您的脚本将与加载图像的线程同时运行。如果您的脚本足够长,或者服务器足够快,并且图像恰好及时到达,您可能不会注意到问题。但最安全的做法是允许加载图像。

document.ready 可能是一个很好的事件,可以让您向用户显示一些“正在加载...”标志,并且在 window.onload 上,您可以完成所需的任何脚本编写资源已加载,然后最后删除“正在加载...”标志。

例子:-

// document ready events
$(document).ready(function(){
     alert("document is ready..");
})

// using JQuery
$(function(){
   alert("document is ready..");
})

// window on load event
function myFunction(){
  alert("window is loaded..");
}
window.onload = myFunction;

The document.ready event occurs when the HTML document has been loaded, and the window.onload event occurs always later, when all content (images, etc) has been loaded.

You can use the document.ready event if you want to intervene "early" in the rendering process, without waiting for the images to load.
If you need the images (or any other "content") ready before your script "does something", you need to wait until window.onload.

For instance, if you are implementing a "Slide Show" pattern, and you need to perform calculations based on image sizes, you may want to wait until window.onload. Otherwise, you might experience some random problems, depending on how fast the images will get loaded. Your script would be running concurrently with the thread that loads images. If your script is long enough, or the server is fast enough, you may not notice a problem, if images happen to arrive in time. But the safest practice would be allowing for images to get loaded.

document.ready could be a nice event for you to show some "loading..." sign to users, and upon window.onload, you can complete any scripting that needed resources loaded, and then finally remove the "Loading..." sign.

Examples :-

// document ready events
$(document).ready(function(){
     alert("document is ready..");
})

// using JQuery
$(function(){
   alert("document is ready..");
})

// window on load event
function myFunction(){
  alert("window is loaded..");
}
window.onload = myFunction;
眼眸印温柔 2024-09-26 19:13:30

时间过得真快,现在已经是 ECMAScript 2021 了,IE11 使用的人越来越少了。对比最多的两个事件是 load DOMContentLoaded

DOMContentLoaded初始 HTML 文档完全加载并解析后触发。

loadDOMContentLoaded 后触发并且整个页面已加载,
等待所有依赖资源完成加载。资源示例:脚本、样式表、图像和 iframe 等。

重要提示:同步脚本将暂停 DOM 解析。

这两个事件都可以用来判断 DOM 是否能够使用。例如:

<script>
    // DOM hasn't been completely parsed
    document.body; // null

    window.addEventListener('DOMContentLoaded', () => {
        // Now safely manipulate DOM
        document.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 too
        document.links;
    });
</script>

Time flies, it's ECMAScript 2021 now and IE11 is used by people less and less. The most two events in contrast are load and DOMContentLoaded.

DOMContentLoaded fires after the initial HTML document has been completely loaded and parsed.

load fires after DOMContentLoaded and the whole page has loaded,
waiting for all dependent resources to finish loading. Example of resources: scripts, stylesheets, images and iframes etc.

IMPORTANT: Synchronous scripts will pause parsing of the DOM.

Both two events can be used to determine the DOM is able to use or not. For examples:

<script>
    // DOM hasn't been completely parsed
    document.body; // null

    window.addEventListener('DOMContentLoaded', () => {
        // Now safely manipulate DOM
        document.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 too
        document.links;
    });
</script>
゛时过境迁 2024-09-26 19:13:30

window.onload 是一个 JavaScript 内置函数。 window.onload 在 HTML 页面加载时触发。 window.onload 只能写入一次。

document.ready 是 jQuery 库的一个函数。 document.ready 当 HTML 以及 HTML 文件中包含的所有 JavaScript 代码、CSS 和图像完全加载时触发。
document.ready可以根据需求多次写入。

window.onload is a JavaScript inbuilt function. window.onload trigger when the HTML page loaded. window.onload can be written only once.

document.ready is a function of the jQuery library. document.ready triggers when HTML and all JavaScript code, CSS, and images which are included in the HTML file are completely loaded.
document.ready can be written multiple times according to requirements.

平定天下 2024-09-26 19:13:30

当您说 $(document).ready(f) 时,您告诉脚本引擎执行以下操作:

  1. 获取对象文档并推送它,因为它不在本地范围内,所以它必须执行哈希表查找查找文档的位置,幸运的是文档是全局绑定的,因此它是单个查找。
  2. 找到对象 $ 并选择它,因为它不在本地范围内,所以它必须执行哈希表查找,这可能会或可能不会发生冲突。
  3. 在全局范围内找到对象 f,这是另一个哈希表查找,或者推送函数对象并初始化它。
  4. 调用所选对象的“ready”,这涉及对所选对象进行另一个哈希表查找以找到方法并调用它。
  5. 完毕。

在最好的情况下,这是 2 个哈希表查找,但这忽略了 jQuery 所做的繁重工作,其中 $ 是 jQuery 所有可能输入的厨房水槽,因此可能会分发另一个映射查询正确的处理程序。

或者,你可以这样做:

window.onload = function() {...}

这将

  1. 在全局范围内找到对象 window ,如果 JavaScript 被优化,它会知道由于 window 没有改变,它已经是选定的对象,所以不需要做任何事情。
  2. 函数对象被压入操作数栈。
  3. 通过查找哈希表来检查 onload 是否是一个属性,因为它是一个属性,所以它像一个函数一样被调用。

在最好的情况下,这会花费一次哈希表查找,这是必要的,因为必须获取 onload

理想情况下,jQuery 会将它们的查询编译为字符串,可以粘贴这些字符串来执行您希望 jQuery 执行的操作,但无需 jQuery 的运行时分派。这样你就可以选择

  1. 像我们今天一样动态调度 jquery。
  2. 让 jQuery 将您的查询编译为纯 JavaScript 字符串,该字符串可以传递给 eval 来执行您想要的操作。
  3. 将 2 的结果直接复制到您的代码中,并跳过 eval 的成本。

When you say $(document).ready(f), you tell script engine to do the following:

  1. get the object document and push it, since it's not in local scope, it must do a hash table lookup to find where document is, fortunately document is globally bound so it is a single lookup.
  2. find the object $ and select it, since it's not in local scope, it must do a hash table lookup, which may or may not have collisions.
  3. find the object f in global scope, which is another hash table lookup, or push function object and initialize it.
  4. call ready of selected object, which involves another hash table lookup into the selected object to find the method and invoke it.
  5. done.

In the best case, this is 2 hash table lookups, but that's ignoring the heavy work done by jQuery, where $ is the kitchen sink of all possible inputs to jQuery, so another map is likely there to dispatch the query to correct handler.

Alternatively, you could do this:

window.onload = function() {...}

which will

  1. find the object window in global scope, if the JavaScript is optimized, it will know that since window isn't changed, it has already the selected object, so nothing needs to be done.
  2. function object is pushed on the operand stack.
  3. check if onload is a property or not by doing a hash table lookup, since it is, it is called like a function.

In the best case, this costs a single hash table lookup, which is necessary because onload must be fetched.

Ideally, jQuery would compile their queries to strings that can be pasted to do what you wanted jQuery to do but without the runtime dispatching of jQuery. This way you have an option of either

  1. do dynamic dispatch of jquery like we do today.
  2. have jQuery compile your query to pure JavaScript string that can be passed to eval to do what you want.
  3. copy the result of 2 directly into your code, and skip the cost of eval.
猫九 2024-09-26 19:13:30

window.onload 由 DOM api 提供,它表示“加载给定资源时将触发加载事件”。

“load 事件在文档加载过程结束时触发。此时,文档中的所有对象都在 DOM 中,并且所有图像、脚本、链接和子框架都已存在加载完毕。”
DOM onload

但是在 jQuery $(document) 中。仅当页面文档对象模型 (DOM) 准备好执行 JavaScript 代码时,ready() 才会运行。这不包括图像、脚本、iframe 等。jquery 就绪事件

因此 jquery Ready 方法将比 dom onload 事件更早运行。

window.onload is provided by DOM api and it says " the load event fires when a given resource has loaded".

"The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading."
DOM onload

But in jQuery $(document).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. This does not include images, scripts, iframes etc. jquery ready event

So the jquery ready method will run earlier than the dom onload event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文