开发者

Why is jQuery syntax used here?

开发者 https://www.devze.com 2023-02-22 04:08 出处:网络
As in this screencast ( http://www.youtube.com/watch?v=h0uZIljjElo ), I think I often see jQuery syntax being used to wrap and define functions that don\'t benefit from jQuery.E.g.:

As in this screencast ( http://www.youtube.com/watch?v=h0uZIljjElo ), I think I often see jQuery syntax being used to wrap and define functions that don't benefit from jQuery. E.g.:

<script>
  $(function() {
    // some code to run at load time
  });
</script>

It would be shorter to write the code without the 2nd and 4th lines. Is there some value in writing after t开发者_开发知识库his fashion?


The code is "benefiting from jQuery" by asking the library not to run it until the entire DOM is ready. For example, if that code is in the <head>, references to the DOM (by "id" or "class" or anything else) generally won't work because the body has not been loaded, and so there are no elements to find.


This statement is a document ready statement, which is basically saying "Please don't run any of the code inside this block until the DOM is ready to be manipulated."


Even if the function is not using JQuery explicitly, it will be executed on the ready event of the document. The same effect could be achieved by using window.onload = function() {} but JQuery's version is better IMHO, because it allows for an arbitrary amount of functions to listen to the ready event.


Well nothing wrong with that only in certain cases you might want to use functions as soon as DOM object you are looking for is there so we leave function outside and use "on*" events asap. But wrapping it in jquery all DOM ready function is just a safer way to write.

0

精彩评论

暂无评论...
验证码 换一张
取 消