+ 1
About the use of the initial $(function(){ ... });
I've also seen the use of, for example: var myFunction = function(){ ...}); and then calling that function at the end using: $(myFunction); Is there a difference between the two techniques? Are they both current? Which is preferred, etc. Thanks all in advance.
2 ответов
+ 6
One is generally used with jQuery, and the other is standard Javascript or "RAW JS" - that's what I call it anyway. I prefer RAW JS as it means I'm not using an additional resource that may lack in terms of performance or speed - as it's a linked script, although jQuery is great for convenience, and has quicker ways to manipulate behaviour. I'm old school so I prefer RJS because I don't remember jQuery being around when I was 16 - 17 and I'm now 27 lol - it's a matter of preference, but do remember that if it's faster use it.
Using jQuery makes it quicker to write:
window.onload = function(){
// when the page has loaded code with RJS
}
is more than
$(function(){
// when the page has loaded code with jQ
}
or
var a = $("#THISID").val();
vs
var a = document.getElementById("THISID").value;
You can clearly see who wins in terms of shorter code.
0
Mark Foxx, you misunderstood my question. It wasn't about choosing to use JQ or JS or which one you prefer. It was clearly about which of the two given ways jQuery code can be 'contained' and therefore executed. Either WITHIN the 'ready' function (method), or in named function and then called using the 'ready' function at the end.
I've seen both uses and wonder if there is any particular reason for having JQ code called from a 'ready' method on the named function (var) at the end.
I hope you understand now. I'm guessing it's just a personal preference issue.