将document.ready绑定到弹出窗口 [英] Bind document.ready to a popout window
问题描述
由于jQuery绑定document.ready
事件的方式,应该简单的代码不是:
Due to the manner in which jQuery binds the document.ready
event, code that should be simple isn't:
var w = window.open(someSameOriginLocation,'');
$(w).ready(function () { //alternatively selector could be $(w.document)
console.log('popout ready');
});
问题
- 在父窗口准备就绪而不是子窗口准备就绪时执行回调 回调
- 是对
w.opener.document
的引用
- the callback executes when the parent window is ready, not the child
- within the callback
this
is a reference tow.opener.document
this
中的
Problems
是否存在使用jQuery将ready
事件(或类似事件)绑定到其他窗口上下文的相当简单的跨浏览器方式?
Is there a reasonably simple, cross-browser way of binding the ready
event (or similar) to a different window context using jQuery?
推荐答案
大约5年前我问这个问题时,我还没有听说过诺言. jQuery 1.7最近已经发布,而Deferred
则是在今年早些时候的1.5中引入的.这早于Promises/A+
规范,而该规范在一年后发布.
When I asked this question about 5 years ago I hadn't heard of promises. jQuery 1.7 had recently been released, and Deferred
had been introduced in 1.5 earlier in the year. This predated the Promises/A+
specification, which was released just over a year later.
之所以这么说是因为当时我无法识别jQuery的$(document).ready(...)
是什么.
I say this all because at the time I had no way of recognizing jQuery's $(document).ready(...)
for what it was.
它被绑定为一个事件,并以回调作为一个事件,而jQuery API将其视为一个事件,所以我错误地认为它是一个事件,尽管这是一个特殊的事件.
It was bound as an event, and took a callback as an event, and the jQuery API treated it as an event, so I had mistakenly assumed it was an event, albeit a special one.
准备好文档不是事件. 这是一个承诺.
所以说了这么多,我的错误是试图跟随jQuery的领导并创建一个盛大的事件,当时我应该做的就是使用一个Promise(不要介意它们在JS世界中还不存在).
So with all that said, my mistake was in attempting to follow jQuery's lead and create a fancy event, when what I should have done was use a promise (never mind that they didn't exist in the JS world yet).
话虽如此,在现代浏览器中的任何窗口引用上都支持类似document.ready
的行为非常简单.我有时间上的优势,因为许多旧问题已被修正,并且新的浏览器功能(例如Promise
)大大减少了实现ready
功能的工作量.
With all that said, supporting a document.ready
-like behavior on any window reference in modern browsers is pretty simple. I have the advantage of time in that many old problems have been bugfixed away, and new browser features (such as Promise
) greatly reduce the amount of effort to implement a ready
function.
我对这个问题的解决方案如下:
My solution to this problem looks like:
function ready(win) {
return new Promise(function (resolve) {
function checkReady() {
if (win.document.readyState === 'complete') {
resolve();
}
}
win.document.addEventListener('DOMContentLoaded', checkReady, false);
win.addEventListener('load', checkReady, false);
checkReady();
});
}
,可以用作:
ready(window).then(function () {
//...do stuff
});
,或者如果您使用的是window.open
:
or if you're using window.open
:
ready(open('/your/file.html', ...)).then(function () {
//.../your/file.html is ready
});
这篇关于将document.ready绑定到弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!