有什么不同
$(document).ready(function(){
//my code here
});
and
$(window).load(function(){
//my code here
});
我想确保:
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
都是一样的。
你能告诉我它们之间有什么异同吗?
来自jQuery API文档
While JavaScript provides the load event for executing code when a
page is rendered, this event does not get triggered until all assets
such as images have been completely received. In most cases, the
script can be run as soon as the DOM hierarchy has been fully
constructed. The handler passed to .ready() is guaranteed to be
executed after the DOM is ready, so this is usually the best place to
attach all other event handlers and run other jQuery code. When using
scripts that rely on the value of CSS style properties, it's important
to reference external stylesheets or embed style elements before
referencing the scripts.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.
第二个问题的答案是
不,只要你不是在无冲突模式下使用jQuery,它们是相同的。
$(文档)时函数(){
//当HTML-Document加载并且DOM准备就绪时执行
Console.log("文档已准备好");
});
$(窗口).load(函数(){
//当整个页面完全加载时执行,包括所有帧,对象和图像
Console.log(“窗口已加载”);
});
< script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>
查询3.0版本
破坏性更改:.load(), .unload()和.error()被删除
这些方法是事件操作的快捷方式,但是有几个API
的局限性。事件的.load()方法与ajax的.load()冲突
方法。.error()方法不能与window.onerror一起使用
因为DOM方法的定义方式。如果你需要附加
事件,使用.on()方法,例如change
$("img").load(fn)到$(img)。(“负载”,fn)。1
$(window).load(function() {});
应改为
$(window).on('load', function (e) {})
这些都是等价的:
$(function(){
});
jQuery(document).ready(function(){
});
$(document).ready(function(){
});
$(document).on('ready', function(){
})
$(document).ready()和$(window).load()函数之间的区别是,$(window).load()中包含的代码将在整个页面(图像,iframes,样式表等)加载后运行,而document ready事件在所有图像,iframes等加载之前触发,但在整个DOM本身准备好之后。
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
以上3个代码没有区别。
它们是等价的,但是如果任何其他JavaScript框架使用相同的美元符号$作为快捷方式名,您可能会面临冲突。
jQuery.noConflict();
jQuery.ready(function($){
//Code using $ as alias to jQuery
});