javascript - 原生 JavaScript document.ready - 如何使用 bindReady()

标签 javascript jquery

我正在寻找 jQuery 的 document.ready() 的原生 JavaScript 解决方案。查看 this thread ,CMS 建议仅使用 jQuery 用于实现其 document.ready() 的 code。我正在查看 bindReady() 但不确定如何将其合并到我的代码中。我目前有这样的东西:

$(document).ready( function() {
    console.log('foo');
});

最佳答案

基本上当你需要做的是替换有

的行
jQuery.ready();

使用您要调用的函数的名称。如果您想要像 jQuery 的现成注册方法那样工作的东西,请构建一个创建队列的函数。当“就绪”被触发时循环遍历队列。


您要求提供更多信息,所以这里是一个不使用超时的快速而简单的示例。这不是生产就绪,只是一个基本的 POC。

    (function () {

        var ready = {
            _readyQueue: [],
            _hasRun: false,
            _docReadyCalled : function() {
                this._hasRun = true;
                this._execute();
            },
            _execute: function () {
                var func;
                while (this._readyQueue.length) {
                    func = this._readyQueue.shift();
                    func();
                }
            },
            register: function (func) {
                this._readyQueue.push(func);
                if (this._hasRun) {
                    this._execute();
                }
            }         
        }

        window.docReady = ready.register.bind(ready);  //use what ever global namespace you want here

        function bindReady() {

            /* This would be that jQuery code, I am just use window load here so not so much code */

            //Not all browser support this, quick and dirty for example
            window.addEventListener('load', ready._docReadyCalled.bind(ready), false);

        }

        bindReady();

    })();


    /* waiting for DOM to be ready */
    docReady(function () { console.log("here"); });
    docReady(function () { console.log("there"); });

    /* Showing what happens when you call docReady after it is ready */
    docReady(function () { console.log("registering ready again"); docReady(function () { console.log("I am here!"); });    });

关于javascript - 原生 JavaScript document.ready - 如何使用 bindReady(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21028335/

相关文章:

javascript - JS : Event when size of element is known

javascript - $(document).ready( function() 中的语句不起作用

javascript - 使用 Angular 过滤器从字符串中删除特殊字符的正则表达式

javascript - 使用 Firefox Add-on SDK 定位面板

javascript - 主干网获取相关模型

javascript - 如何在 backbone.js 回调中从模型中分离一些响应数据

javascript - 是否可以结合 document.ready 功能和按钮点击功能?

javascript - 用变量预填充 HTML 值?

javascript - 业力 + Webpack2 : module parse failed and imports not found

javascript - 如何使用 CasperJS 将 html 数据表解析/映射到 JSON 对象?