0

i am buliding an autocomplete for my website when i came across this style of building code:

$(function() {

    function log( message ) {
        $( "<div/>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $(element).autocomplete(....

    //more code
});

i know about closures, "IIFE"s but this one's a new one for me.

  • what's with the "jQuery-wrapped" code above?
  • is there any particular reason i should do that? (scope?)
  • optimization-wise, should i even do it that way?

3 Answers 3

2
  1. $(function() { }); is equivalent to $(document).ready(function() {}); and as before it executes once the DOM has been ready.

  2. Defining a function inside is to tell that, the function is only available once the dom is ready to execute.

  3. $(element).autocomplete(.... is simply implementing the plugin to the selector, once the DOM is ready to execute.

Hope its clear now :)


$(function() { or $(document).ready(function() { does not need the whole page to load, to run as $(window).load(fn) does.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! never knew that it was just a shorthand to .ready()
1

$(fn) or $(document).ready(fn) Is jQuery's onload/onDOMContentLoaded handler. The function passed to it is executed once the DOM on the page is ready.

Comments

1

Everything in $(function() { } will be executed after the DOM has loaded. I prefer to use $(document).ready(function() { } because it is more clear.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.