我正在寻找 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/