有什么不同
$(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
});
美元(窗口)。load是一个事件,当DOM和页面上的所有内容(所有内容)完全加载时,如CSS、图像和帧。一个最好的例子是,如果我们想要得到实际的图像大小或任何细节,我们使用它。
$(document).ready()表示其中的代码需要在DOM加载并准备由脚本操作时执行。它不会等待图像加载后执行jQuery脚本。
<script type = "text/javascript">
//$(window).load was deprecated in 1.8, and removed in jquery 3.0
// $(window).load(function() {
// alert("$(window).load fired");
// });
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
美元(窗口)。在$(document).ready()之后加载。
$(document).ready(function(){
})
//and
$(function(){
});
//and
jQuery(document).ready(function(){
});
以上3个是一样的,$是jQuery的别名,如果其他JavaScript框架使用相同的$符号,你可能会面临冲突。如果你面临冲突,jQuery团队提供了一个无冲突的解决方案。
美元(窗口)。Load在1.8中已弃用,在jquery 3.0中被移除