javascript - $(document).ready 相当于没有 jQuery

标签 javascript jquery pageload

我有一个使用 $(document).ready 的脚本,但它不使用 jQuery 中的任何其他内容。我想通过删除 jQuery 依赖来减轻它的负担。

如何在不使用 jQuery 的情况下实现我自己的 $(document).ready 功能?我知道使用 window.onload 会不一样,因为 window.onload 在加载所有图像、帧等后触发。

最佳答案

有一个基于标准的替代品,DOMContentLoaded,超过 99% of browsers 支持该替代品。 ,虽然不是 IE8:

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

jQuery 的原生函数比 window.onload 复杂得多,如下所示。

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}

关于javascript - $(document).ready 相当于没有 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36286642/

相关文章:

javascript - HTML5 响应式网站,需要在小屏幕上自动滚动以跳过导航

javascript - 隐藏与空文本区域相关的按钮(选择问题)

jquery - NProgress.js 显示页面加载进度

javascript - Cypress : `cy.contains` 和 `cy. findByText` 有什么区别

javascript - 加载 Atom.io 包中的 HTML 文件

javascript - SVG 可以有多个开始或结束触发器吗?

javascript - 使用 Javascript/JQuery 迭代 JSON 响应

javascript - JSON : The request sent by the client was syntactically incorrect

python - 加快 django 中的首页加载速度

c# - 在同一页面上当我单击 Save_button 时,应该执行 firSTLy Page_Load 事件还是 btnSave_Click 按钮?