我有一个可以在网页生命周期的任何阶段加载的脚本。 加载脚本时,它必须运行initialize()方法。
我希望这个函数在“onload”事件上运行,但我不能确定该页面尚未加载,即“onload”尚未被解雇。
理想情况下,我的脚本看起来像这样:
var _initialize = function() { ...};
if(window.LOADED)
_initialize();
else if (window.addEventListener)
window.addEventListener('load', _initialize, false);
else if (window.attachEvent)
window.attachEvent('onload', _initialize);
是否有这样的window.LOADED或document.LOADED变量或类似的东西?
提前致谢, 沙恩
答案 0 :(得分:4)
您可以使用jQuery来执行此操作。 $(document).ready()
。查看this
只需在准备好的内部调用您想要的功能。然后它将在文档完全加载后执行
答案 1 :(得分:1)
如果您没有使用任何库,则可以使用此
function somelib(){
this.readystate = false; //tracks the state of DOM
var nextcallfunc; //stores the function to be called after DOM is loaded
//called by checkReady function when DOM is loaded completely
this.ready = function(func){
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
this.readystate=true; //make DOM load permanent
nextcallfunc.call(); //calls the onload handler
}
//Checks if the DOM has loaded or not
this.checkReady= function(func){
/* for Mozilla/Opera9 */
nextcallfunc = func;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", this.ready , false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
ready(func); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
this.ready(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = this.ready;
}
}
这也解决了跨浏览器问题..
答案 2 :(得分:0)
这就是我所做的(用CoffeeScript编写):
$(window).on 'load', ->
window._loaded = true
window.on_window_load_safe = (callback) ->
if window._loaded
# Since the load even already happened, if we tried to add a new callback now, it would not even
# get called. So just call the callback immediately now.
callback.call()
else
$(window).on 'load', ->
callback.call()
您可以使用以下内容进行测试:
setTimeout(->
on_window_load_safe ->
console.debug 'on_window_load_safe called me'
, 2000)
答案 3 :(得分:-2)
你可以使用
jQuery(document).ready();
在页面的末尾或标签之前,它会在您的网页显示在客户端计算机上时大约在加载结束时显示.....