我可以在document.ready()上获得一个延迟的jQuery吗?

Daf*_*aff 21 ajax jquery jquery-deferred

我的脚本加载后,我正在发出Ajax请求以获得一些翻译.这应该总是在文档准备好后返回,因为我在页面底部加载我的脚本,但我仍然很好奇是否可以在文档就绪状态下获得延迟对象.

这样就可以确保文档准备就绪并且Ajax调用在执行任何其他操作之前成功返回,例如:

$.when( $.ajax('translations'), document.ready())
.then(function(){
    // Start doing stuff here
});
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 23

您可以使用data()将延迟对象与文档关联,并在处理程序中解析()ready.这样,您应该能够使用$ .when()使用存储的延迟对象:

$(document).data("readyDeferred", $.Deferred()).ready(function() {
    $(document).data("readyDeferred").resolve();
});

$.when($.ajax("translations"), $(document).data("readyDeferred"))
 .then(function() {
    // Start doing stuff here.
});
Run Code Online (Sandbox Code Playgroud)

  • 迂腐的笔记.根本没有理由存储变量.您只需在设置阶段使用它,因此请使用闭包范围:`(function(){var deferred = new $ .Deferred(); $(function(){deferred.resolve();}); $ .when($. ajax('foo'),deferred).then(function(){});})();`...如果使用本地作用域,则无需存储,只需让闭包为你绑定它. . (8认同)

zai*_*ius 19

这是ircmaxell评论的清理版本:

(function() {
  var doc_ready = $.Deferred();
  $(doc_ready.resolve);
  $.when(doc_ready, $.ajax('translations')).then(function() {
    console.log("done");
  });
})();
Run Code Online (Sandbox Code Playgroud)

编辑

一些澄清,以阻止不正确的编辑:

将函数传递给jquery对象(例如$(some_func))与$(document).ready(some_func).

因此,该$(doc_ready.resolve);行只是这样的简写:

$(document).ready(function() {
  doc_ready.resolve()
});
Run Code Online (Sandbox Code Playgroud)


tho*_*rn̈ 9

试试这个:

$.when($.ajax('translations'), $.ready).then(function() {
    // Start doing stuff here
});
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`$ .ready`实际上并不是延迟的,但碰巧有一个`promise`方法. (3认同)

Vla*_*sky 6

我的版本是:

$.when(
  $.Deferred(function() { $(this.resolve); }), 
  $.ajax('translations')).
  then(function() { console.log("done"); });
Run Code Online (Sandbox Code Playgroud)