代码之家  ›  专栏  ›  技术社区  ›  FlySwat

$(document).ready等同于没有jquery

  •  1761
  • FlySwat  · 技术社区  · 17 年前

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

    我如何实现我自己的 $(文档)。就绪 不使用jquery的功能?我知道使用 window.onload 将不相同,因为 上载窗口 加载所有图像、帧等后激发。

    33 回复  |  直到 7 年前
        1
  •  1175
  •   Abhi Beckert    9 年前

    有一个基于标准的替代品, DOMContentLoaded 得到了更多的支持 98% 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 );
    }
    
        2
  •  310
  •   Timo Huovinen    7 年前

    编辑:

    这里有一个可以替代jquery的可行方案。

    function ready(callback){
        // in case the document is already rendered
        if (document.readyState!='loading') callback();
        // modern browsers
        else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
        // IE <= 8
        else document.attachEvent('onreadystatechange', function(){
            if (document.readyState=='complete') callback();
        });
    }
    
    ready(function(){
        // do something
    });
    

    取自 https://plainjs.com/javascript/events/running-code-when-the-document-is-ready-15/

    Another good domReady function here 取自 https://stackoverflow.com/a/9899701/175071


    由于接受的答案还远远不够完整,我把“准备好”的功能缝在一起,就像 jQuery.ready() 基于jquery 1.6.2,来源:

    var ready = (function(){
    
        var readyList,
            DOMContentLoaded,
            class2type = {};
            class2type["[object Boolean]"] = "boolean";
            class2type["[object Number]"] = "number";
            class2type["[object String]"] = "string";
            class2type["[object Function]"] = "function";
            class2type["[object Array]"] = "array";
            class2type["[object Date]"] = "date";
            class2type["[object RegExp]"] = "regexp";
            class2type["[object Object]"] = "object";
    
        var ReadyObj = {
            // Is the DOM ready to be used? Set to true once it occurs.
            isReady: false,
            // A counter to track how many items to wait for before
            // the ready event fires. See #6781
            readyWait: 1,
            // Hold (or release) the ready event
            holdReady: function( hold ) {
                if ( hold ) {
                    ReadyObj.readyWait++;
                } else {
                    ReadyObj.ready( true );
                }
            },
            // Handle when the DOM is ready
            ready: function( wait ) {
                // Either a released hold or an DOMready/load event and not yet ready
                if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
                    // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                    if ( !document.body ) {
                        return setTimeout( ReadyObj.ready, 1 );
                    }
    
                    // Remember that the DOM is ready
                    ReadyObj.isReady = true;
                    // If a normal DOM Ready event fired, decrement, and wait if need be
                    if ( wait !== true && --ReadyObj.readyWait > 0 ) {
                        return;
                    }
                    // If there are functions bound, to execute
                    readyList.resolveWith( document, [ ReadyObj ] );
    
                    // Trigger any bound ready events
                    //if ( ReadyObj.fn.trigger ) {
                    //    ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
                    //}
                }
            },
            bindReady: function() {
                if ( readyList ) {
                    return;
                }
                readyList = ReadyObj._Deferred();
    
                // Catch cases where $(document).ready() is called after the
                // browser event has already occurred.
                if ( document.readyState === "complete" ) {
                    // Handle it asynchronously to allow scripts the opportunity to delay ready
                    return setTimeout( ReadyObj.ready, 1 );
                }
    
                // Mozilla, Opera and webkit nightlies currently support this event
                if ( document.addEventListener ) {
                    // Use the handy event callback
                    document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                    // A fallback to window.onload, that will always work
                    window.addEventListener( "load", ReadyObj.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", DOMContentLoaded );
    
                    // A fallback to window.onload, that will always work
                    window.attachEvent( "onload", ReadyObj.ready );
    
                    // If IE and not a frame
                    // continually check to see if the document is ready
                    var toplevel = false;
    
                    try {
                        toplevel = window.frameElement == null;
                    } catch(e) {}
    
                    if ( document.documentElement.doScroll && toplevel ) {
                        doScrollCheck();
                    }
                }
            },
            _Deferred: function() {
                var // callbacks list
                    callbacks = [],
                    // stored [ context , args ]
                    fired,
                    // to avoid firing when already doing so
                    firing,
                    // flag to know if the deferred has been cancelled
                    cancelled,
                    // the deferred itself
                    deferred  = {
    
                        // done( f1, f2, ...)
                        done: function() {
                            if ( !cancelled ) {
                                var args = arguments,
                                    i,
                                    length,
                                    elem,
                                    type,
                                    _fired;
                                if ( fired ) {
                                    _fired = fired;
                                    fired = 0;
                                }
                                for ( i = 0, length = args.length; i < length; i++ ) {
                                    elem = args[ i ];
                                    type = ReadyObj.type( elem );
                                    if ( type === "array" ) {
                                        deferred.done.apply( deferred, elem );
                                    } else if ( type === "function" ) {
                                        callbacks.push( elem );
                                    }
                                }
                                if ( _fired ) {
                                    deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
                                }
                            }
                            return this;
                        },
    
                        // resolve with given context and args
                        resolveWith: function( context, args ) {
                            if ( !cancelled && !fired && !firing ) {
                                // make sure args are available (#8421)
                                args = args || [];
                                firing = 1;
                                try {
                                    while( callbacks[ 0 ] ) {
                                        callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
                                    }
                                }
                                finally {
                                    fired = [ context, args ];
                                    firing = 0;
                                }
                            }
                            return this;
                        },
    
                        // resolve with this as context and given arguments
                        resolve: function() {
                            deferred.resolveWith( this, arguments );
                            return this;
                        },
    
                        // Has this deferred been resolved?
                        isResolved: function() {
                            return !!( firing || fired );
                        },
    
                        // Cancel
                        cancel: function() {
                            cancelled = 1;
                            callbacks = [];
                            return this;
                        }
                    };
    
                return deferred;
            },
            type: function( obj ) {
                return obj == null ?
                    String( obj ) :
                    class2type[ Object.prototype.toString.call(obj) ] || "object";
            }
        }
        // The DOM ready check for Internet Explorer
        function doScrollCheck() {
            if ( ReadyObj.isReady ) {
                return;
            }
    
            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch(e) {
                setTimeout( doScrollCheck, 1 );
                return;
            }
    
            // and execute any waiting functions
            ReadyObj.ready();
        }
        // Cleanup functions for the document ready method
        if ( document.addEventListener ) {
            DOMContentLoaded = function() {
                document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                ReadyObj.ready();
            };
    
        } else if ( document.attachEvent ) {
            DOMContentLoaded = function() {
                // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                if ( document.readyState === "complete" ) {
                    document.detachEvent( "onreadystatechange", DOMContentLoaded );
                    ReadyObj.ready();
                }
            };
        }
        function ready( fn ) {
            // Attach the listeners
            ReadyObj.bindReady();
    
            var type = ReadyObj.type( fn );
    
            // Add the callback
            readyList.done( fn );//readyList is result of _Deferred()
        }
        return ready;
    })();
    

    如何使用:

    <script>
        ready(function(){
            alert('It works!');
        });
        ready(function(){
            alert('Also works!');
        });
    </script>
    

    我不确定这段代码的功能,但它在我的表面测试中运行得很好。这花了很长时间,所以我希望你和其他人能从中受益。

    PS.:我建议。 compiling 它。

    或者你可以使用 http://dustindiaz.com/smallest-domready-ever :

    function r(f){/in/.test(document.readyState)?setTimeout(r,9,f):f()}
    r(function(){/*code to run*/});
    

    或者,如果只需要支持新的浏览器,则使用本机函数(与jquery ready不同,如果在页面加载后添加此函数,则不会运行此函数)

    document.addEventListener('DOMContentLoaded',function(){/*fun code to run*/})
    
        3
  •  193
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    三种选择:

    1. 如果 script 是主体的最后一个标记,在脚本标记执行之前,DOM将准备就绪。
    2. 当DOM就绪时,“readystate”将更改为“complete”
    3. 将所有内容置于“domcontentloaded”事件侦听器下

    OnReadyStateChange(状态更改)

      document.onreadystatechange = function () {
         if (document.readyState == "complete") {
         // document is ready. Do your stuff here
       }
     }
    

    来源: MDN

    已加载domcontentloaded

    document.addEventListener('DOMContentLoaded', function() {
       console.log('document is ready. I can sleep now');
    });
    

    关注石器时代的浏览器: 转到jquery源代码并使用 ready 功能。在这种情况下,您不需要解析+执行整个库,而只需要执行其中很小的一部分。

        4
  •  84
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    放置你的 <script>/*JavaScript code*/</script> 正确的 收盘前 </body> 标签。

    不可否认,这可能不适合每个人的目的,因为它需要更改HTML文件,而不仅仅是在JavaScript文件中执行一些操作。 document.ready 但仍然…

        5
  •  67
  •   RevanthKrishnaKumar V. Glen Best    11 年前

    穷人的解决方案:

    var checkLoad = function() {   
        document.readyState !== "complete" ? setTimeout(checkLoad, 11) : alert("loaded!");   
    };  
    
    checkLoad();  
    

    View Fiddle

    加上了这个,我想更好一点,有自己的作用域和非递归

    (function(){
        var tId = setInterval(function() {
            if (document.readyState == "complete") onComplete()
        }, 11);
        function onComplete(){
            clearInterval(tId);    
            alert("loaded!");    
        };
    })()
    

    View Fiddle

        6
  •  33
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    我用这个:

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

    注意:这可能只适用于较新的浏览器,尤其是以下浏览器: http://caniuse.com/#feat=domcontentloaded

        7
  •  20
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    真的,如果你在乎的话 Internet Explorer 9+ 仅此代码足以替换 jQuery.ready :

        document.addEventListener("DOMContentLoaded", callback);
    

    如果你担心 Internet Explorer 6 还有一些非常奇怪和罕见的浏览器,这将起作用:

    domReady: function (callback) {
        // Mozilla, Opera and WebKit
        if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", callback, false);
            // If Internet Explorer, the event model is used
        } else if (document.attachEvent) {
            document.attachEvent("onreadystatechange", function() {
                if (document.readyState === "complete" ) {
                    callback();
                }
            });
            // A fallback to window.onload, that will always work
        } else {
            var oldOnload = window.onload;
            window.onload = function () {
                oldOnload && oldOnload();
                callback();
            }
        }
    },
    
        8
  •  17
  •   RevanthKrishnaKumar V. Glen Best    11 年前

    这个问题很久以前就被问到了。对于任何刚刚看到这个问题的人,现在有一个叫做 "you might not need jquery" 它按所需的IE支持级别分解了jquery的所有功能,并提供了一些可选的、较小的库。

    IE8文档就绪脚本 you might not need jquery

    function ready(fn) {
        if (document.readyState != 'loading')
            fn();
        else if (document.addEventListener)
            document.addEventListener('DOMContentLoaded', fn);
        else
            document.attachEvent('onreadystatechange', function() {
                if (document.readyState != 'loading')
                    fn();
            });
    }
    
        9
  •  13
  •   SeanCannon    14 年前

    我最近用这个做手机网站。这是John Resig从“pro-javascript技术”得到的简化版本。这取决于addevent。

    var ready = ( function () {
      function ready( f ) {
        if( ready.done ) return f();
    
        if( ready.timer ) {
          ready.ready.push(f);
        } else {
          addEvent( window, "load", isDOMReady );
          ready.ready = [ f ];
          ready.timer = setInterval(isDOMReady, 13);
        }
      };
    
      function isDOMReady() {
        if( ready.done ) return false;
    
        if( document && document.getElementsByTagName && document.getElementById && document.body ) {
          clearInterval( ready.timer );
          ready.timer = null;
          for( var i = 0; i < ready.ready.length; i++ ) {
            ready.ready[i]();
          }
          ready.ready = null;
          ready.done = true;
        }
      }
    
      return ready;
    })();
    
        10
  •  11
  •   Miere    13 年前

    jquery的答案对我很有用。只需稍加重构,就可以很好地满足我的需要。 我希望它能帮助任何人。

    function onReady ( callback ){
        var addListener = document.addEventListener || document.attachEvent,
            removeListener =  document.removeEventListener || document.detachEvent
            eventName = document.addEventListener ? "DOMContentLoaded" : "onreadystatechange"
    
        addListener.call(document, eventName, function(){
            removeListener( eventName, arguments.callee, false )
            callback()
        }, false )
    }
    
        11
  •  10
  •   Pawel    10 年前

    跨浏览器(也是旧浏览器)和一个简单的解决方案:

    var docLoaded = setInterval(function () {
        if(document.readyState !== "complete") return;
        clearInterval(docLoaded);
    
        /*
            Your code goes here i.e. init()
        */
    }, 30);
    

    Showing alert in jsfiddle

        12
  •  9
  •   Community Mohan Dere    9 年前

    这里是 测试DOM就绪的最小代码段 适用于所有浏览器(甚至是IE 8):

    r(function(){
        alert('DOM Ready!');
    });
    function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
    

    看到这个 answer .

        13
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    只需将它添加到HTML页面的底部…

    <script>
        Your_Function();
    </script>
    

    因为,HTML文档是由顶部和底部来解析的。

        14
  •  4
  •   Max Heiber    11 年前

    一旦DOM就绪,此跨浏览器代码将调用函数:

    var domReady=function(func){
        var scriptText='('+func+')();';
        var scriptElement=document.createElement('script');
        scriptElement.innerText=scriptText;
        document.body.appendChild(scriptElement);
    };
    

    它的工作原理如下:

    1. 第一行 domReady 调用 toString 方法获取传入函数的字符串表示形式,并将其包装为立即调用该函数的表达式。
    2. 其余的 多米德 使用表达式创建脚本元素并将其附加到 body 文件。
    3. 浏览器运行附加到的脚本标记 身体 在DOM准备好之后。

    例如,如果您这样做: domReady(function(){alert();}); ,以下内容将附加到 身体 元素:

     <script>(function (){alert();})();</script>
    

    注意,这只适用于用户定义的函数。以下内容不起作用: domReady(alert);

        15
  •  4
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    值得一看 Rock Solid addEvent() http://www.braksator.com/how-to-make-your-own-jquery .

    这是万一网站瘫痪的代码

    function addEvent(obj, type, fn) {
        if (obj.addEventListener) {
            obj.addEventListener(type, fn, false);
            EventCache.add(obj, type, fn);
        }
        else if (obj.attachEvent) {
            obj["e"+type+fn] = fn;
            obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
            obj.attachEvent( "on"+type, obj[type+fn] );
            EventCache.add(obj, type, fn);
        }
        else {
            obj["on"+type] = obj["e"+type+fn];
        }
    }
    
    var EventCache = function(){
        var listEvents = [];
        return {
            listEvents : listEvents,
            add : function(node, sEventName, fHandler){
                listEvents.push(arguments);
            },
            flush : function(){
                var i, item;
                for(i = listEvents.length - 1; i >= 0; i = i - 1){
                    item = listEvents[i];
                    if(item[0].removeEventListener){
                        item[0].removeEventListener(item[1], item[2], item[3]);
                    };
                    if(item[1].substring(0, 2) != "on"){
                        item[1] = "on" + item[1];
                    };
                    if(item[0].detachEvent){
                        item[0].detachEvent(item[1], item[2]);
                    };
                    item[0][item[1]] = null;
                };
            }
        };
    }();
    
    // Usage
    addEvent(window, 'unload', EventCache.flush);
    addEvent(window, 'load', function(){alert("I'm ready");});
    
        16
  •  3
  •   mike    14 年前

    这个解决方案怎么样?

    // other onload attached earlier
    window.onload=function() {
       alert('test');
    };
    
    tmpPreviousFunction=window.onload ? window.onload : null;
    
    // our onload function
    window.onload=function() {
       alert('another message');
    
       // execute previous one
       if (tmpPreviousFunction) tmpPreviousFunction();
    };
    
        17
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    与jquery相比,使用JavaScript等价物总是很好的。一个原因是需要依赖的库少了一个,而且它们比jquery等价物快得多。

    jquery等价物的一个非常好的参考是 http://youmightnotneedjquery.com/ .

    关于您的问题,我从上面的链接中获取了以下代码:) 唯一需要注意的是,它只适用于 Internet Explorer 9 后来。

    function ready(fn) {
        if (document.readyState != 'loading') {
            fn();
        }
        else {
            document.addEventListener('DOMContentLoaded', fn);
        }
    }
    
        18
  •  2
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    我们发现了一个快速而肮脏的跨浏览器实现,它可以在实现最少的情况下为大多数简单的情况提供帮助:

    window.onReady = function onReady(fn){
        document.body ? fn() : setTimeout(function(){ onReady(fn);},50);
    };
    
        19
  •  2
  •   Diego Perini    10 年前

    这里介绍的setTimeout/setInterval解决方案只能在特定情况下工作。

    这个问题尤其出现在旧版本的Internet Explorer(最多8个)中。

    影响这些设置超时/设置间隔解决方案成功的变量有:

    1) dynamic or static HTML
    2) cached or non cached requests
    3) size of the complete HTML document
    4) chunked or non chunked transfer encoding
    

    解决此特定问题的原始(本机javascript)代码如下:

    https://github.com/dperini/ContentLoaded
    http://javascript.nwbox.com/ContentLoaded (test)
    

    这是jquery团队从中构建实现的代码。

        20
  •  1
  •   Olemak    10 年前

    这是我使用的,它速度快,涵盖了我认为的所有基础;适用于除IE<9以外的所有东西。

    (() => { function fn() {
        // "On document ready" commands:
        console.log(document.readyState);
    };  
      if (document.readyState != 'loading') {fn()}
      else {document.addEventListener('DOMContentLoaded', fn)}
    })();
    

    这似乎适用于所有情况:

    • 如果DOM已经准备好,则立即激发(如果DOM不是“正在加载”,而是“交互式”或“完成”)。
    • 如果DOM仍在加载,它将为当DOM 可用(交互式)。

    domcontentloaded事件在IE9和其他所有工具中都可用,所以我个人认为可以使用它。如果您没有将代码从ES2015发送到ES5,请将arrow函数声明重写为常规匿名函数。

    如果要等到加载完所有资产、显示的所有图像等,请改用window.onload。

        21
  •  1
  •   user4617883    8 年前

    如果您不需要支持非常老的浏览器,这里有一种方法可以做到这一点,即使在加载外部脚本时 异步的 属性:

    HTMLDocument.prototype.ready = new Promise(function(resolve) {
       if(document.readyState != "loading")
          resolve();
       else
          document.addEventListener("DOMContentLoaded", function() {
             resolve();
          });
    });
    
    document.ready.then(function() {
       console.log("document.ready");
    });
    
        22
  •  1
  •   Dexygen    8 年前

    我简单地使用:

    setTimeout(function(){
        //reference/manipulate DOM here
    });
    

    而且不像 document.addEventListener("DOMContentLoaded" //etc 正如最重要的答案一样,它可以追溯到IE9。-- http://caniuse.com/#search=DOMContentLoaded 仅表示最近的IE11。

    例如,转到 https://netrenderer.com/index.php ,从下拉列表中选择Internet Explorer 9,输入 https://dexygen.github.io/blog/oct-2017/jekyll/jekyll-categories/liquid-templates/2017/10/22/how-jekyll-builds-site-categories.html 点击“渲染”,你会看到一些类似于文章底部截图的东西。

    请参阅下面的javascript代码,我在标题中使用它来操作jekyll“hacker”主题的样式,这是我喜欢的——特别是您可以参考 if (location.pathname !== rootPath) 阻止以查看如何插入 Home Blog Home 链接,由IE9显示在每个NetRenderer站点上。

    有趣的是我偶然发现了这个 setTimeout 2009年的解决方案: Is checking for the readiness of the DOM overkill? 它的措辞可能稍微好一点,正如我所说的使用各种框架的更复杂的方法。

    setTimeout(function() {//delay execution until after dom is parsed
        var containerEls = document.getElementsByClassName('container');
        var headingEl = containerEls[0].getElementsByTagName('h1')[0];
        var headerEl = document.getElementsByTagName('header')[0];
        var downloadsSectionEl = document.getElementById('downloads');
        var rootPath = "/";
        var blogRootPath = "/blog/";
    
        containerEls[0].style.maxWidth = '800px';
        containerEls[1].style.maxWidth = '800px';
        headingEl.style.margin = '0';
        headerEl.style.marginBottom = '7px';
        downloadsSectionEl.style.margin = '0';
    
        if (location.pathname !== rootPath) {
            downloadsSectionEl.appendChild(generateNavLink('Home', rootPath));
            if (location.pathname !== blogRootPath) {
                downloadsSectionEl.appendChild(document.createTextNode(' | '));
                downloadsSectionEl.appendChild(generateNavLink('Blog Home', blogRootPath));
            }
        }
    
        function generateNavLink(linkText, hrefPath) {
            var navLink = document.createElement('a');
            var linkTextNode = document.createTextNode(linkText);
            navLink.setAttribute('href', hrefPath);
            navLink.appendChild(linkTextNode);
            return navLink;
        }
    });
    

    dexygen.github.io on IE9

        23
  •  0
  •   Joaquinglezsantos    10 年前

    对于IE9+:

    function ready(fn) {
      if (document.readyState != 'loading'){
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    }
    
        24
  •  0
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    如果您在正文底部附近加载jquery,但在编写jquery(<func>)或jquery(document).ready(<func>)代码时遇到问题,请签出 jqShim 在吉瑟布上。

    与其重新创建自己的文档就绪函数,不如简单地保留函数,直到jquery可用,然后按预期继续jquery。将jquery移动到正文底部的目的是加快页面加载速度,您仍然可以通过在模板头部嵌入jqshim.min.js来完成这一点。

    最后我编写了这段代码来移动所有脚本 WordPress 到页脚,现在只有这个填充代码直接位于页眉中。

        25
  •  0
  •   Javier Rey    9 年前

    这种方法是我能想到的最短的方法。

    基于domcontentloaded事件的解决方案仅在脚本在文档之前加载时才起作用,而这里建议的惰性检查确保始终执行代码,即使是在以后动态加载的脚本中,也与jquery的文档完全相同。

    此代码与所有浏览器都兼容(包括一些传统浏览器,直至IE6和Safari for Windows)。

    (function ready() {
        if (!document.body) {setTimeout(ready, 50); return;}
        // Document is ready here
    })();
    
        26
  •  0
  •   tnyfst    8 年前

    中的就绪函数 jQuery 做了很多事情。坦率地说,我不认为要取代它,除非你的网站有惊人的小输出。 JQuery 这是一个非常小的库,它可以处理各种各样的跨浏览器的东西,您稍后将需要这些东西。

    不管怎样,把它贴在这里没什么意义,只要打开 JQuery 看看 bindReady 方法。

    它首先调用 document.addEventListener("DOMContentLoaded") document.attachEvent('onreadystatechange') 取决于事件模型,然后继续。

        27
  •  0
  •   user8903269    8 年前

    试试这个:

    function ready(callback){
        if(typeof callback === "function"){
            document.addEventListener("DOMContentLoaded", callback);
            window.addEventListener("load", callback);
        }else{
            throw new Error("Sorry, I can not run this!");
        }
    }
    ready(function(){
        console.log("It worked!");
    });
    
        28
  •  0
  •   Jakob Sternberg    8 年前
    function onDocReady(fn){ 
        $d.readyState!=="loading" ? fn():document.addEventListener('DOMContentLoaded',fn);
    }
    
    function onWinLoad(fn){
        $d.readyState==="complete") ? fn(): window.addEventListener('load',fn);
    } 
    

    OndoCeDead 当HTML DOM准备好完全访问/分析/操作时提供回调。

    欧文负载 在加载所有内容(图像等)时提供回调

    • 您可以随时调用这些函数。
    • 支持多个“监听器”。
    • 可以在任何浏览器中使用。
        29
  •  -1
  •   Community Mohan Dere    9 年前

    这是个好消息 https://stackoverflow.com/a/11810957/185565 可怜人的解决办法。一条评论认为这是紧急情况下的紧急救援措施。这是我的修改。

    function doTheMagic(counter) {
      alert("It worked on " + counter);
    }
    
    // wait for document ready then call handler function
    var checkLoad = function(counter) {
      counter++;
      if (document.readyState != "complete" && counter<1000) {
        var fn = function() { checkLoad(counter); };
        setTimeout(fn,10);
      } else doTheMagic(counter);
    };
    checkLoad(0);
    
        30
  •  -1
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    编辑@duskwuff的编辑以支持 Internet Explorer 8 也是。不同之处在于对regex的函数测试和具有匿名函数的setTimeout的新调用。

    另外,我将超时设置为99。

    function ready(f){/in/.test(document.readyState)?setTimeout(function(){ready(f);},99):f();}