简体   繁体   中英

Should a Javascript function be written and called inside jQuery document ready or outside?

I just have a question about writing functions in jQuery. When defining your own functions should they be written inside $(function(){}); or outside it? Please note that these are just example functions and could be anything. I chose a jQuery function and a native JavaScript to see if there are any differences ie should a self-defined jQuery function be defined inside document ready?

For example:

$(function(){
    $('select').jQueryExample();
    nativeExample();    
});

$.fn.jQueryExample = function(){
    //Do something
}

function nativeExample(a, b)
{   
    return a + b;
}

As opposed to this where they are called AND defined in document ready?

$(function(){
    $('select').jQueryExample();
    nativeExample();

    $.fn.jQueryExample = function(){
        //Do something
    }

    function nativeExample(a, b)
    {   
        return a + b;
    }
});

::EDIT::

One extra question. If a function is defined outside document ready and also called outside document ready, what would happen as opposed to having it defined outside but called inside document ready?

I am asking this because I have a function defined outside the document ready scope and this function is an ajax call which gets new messages on page load. Should it be called outside or inside document ready?

For example:

$(function(){
 //Hello, I am jQuery

});

nativeExample();

function nativeExample(a, b)
{   
    return a + b;
}

as opposed to:

$(function(){

 nativeExample();

});


function nativeExample(a, b)
{   
    return a + b;
}

Thanks in advance for replying.

I think you should defined your functions outside the jQuery ready method, because:

  • the function definition code is a "passive" code: it doesn't need the DOM to be runt
  • if you want to use your function before the ready event, you can't do it if the function is defined inside the event,
  • the jQuery ready method should be used only when it's really needed, it means when you * really have to wait for the DOM to be ready

For information, here is a simplified but common HTML page pattern that I use every time, it works pretty well:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Page title</title>
    <!-- your CSS code -->
    <link rel="stylesheet" href="/path/to/file.css">
</head>
<body>
    <!-- your HTML elements -->

    <!-- all your scripts elements at the bottom -->

    <!-- load jQuery from Google CDN -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

    <!-- load all your "passive" code that defines custom or vendor jQuery plugins -->
    <script src="jquery.plugins.js"></script>

    <!-- load all your "active" code -->
    <script src="yourcode.js"></script>
</body>
</html>

The jquery.plugins.js file could contains something like you provided:

// define all jQuery plugin, aka "passive" code
// "passive" means it won't affect the page
$.fn.jQueryExample = function(){
    //Do something
};

$.fn.somePlugin = function(){
    // Do something
};

// you could define vanilla JavaScript functions in a separated file if you want
function nativeExample(a, b)
{
    return a + b;
}

The file yourcode.js could be:

// place here all "active" code
// by "active" code I mean all code that will interact/alter/modify your page
$(function(){
    $('select').jQueryExample();
    nativeExample();    
});

About your edit, your question what would happen as opposed to having it defined outside but called inside document ready doesn't have a universal answer. Look at this example:

<!-- basic html setup -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Page title</title>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
        // placing <script> tag in the <head> tag is considered as a bad practice
        // I use it for the example but you should not do the same in real code

        // define your functionsin the <head> tag
        function getFoo() {
            return "foo";
        }
        function getAnchor() {
            return document.getElementsByTagName('a');
        }
    </script>

    <script>
        // reference: ONE
        // call your function in the <head> tag
        console.log( "one", getFoo() ); // "foo"
        console.log( "one", getAnchor() ); // empty array
    </script>
    <script>
        // reference: TWO
        $(document).ready(function(){
            // call your function inside the jQuery 'ready' event
            console.log( "two", getFoo() ); // "foo"
            console.log( "two", getAnchor() ); // array with one element
        });
    </script>
</head>
<body>

    <a href="www.example.com">bar</a>


    <script>
        // reference: THREE
        // call your function at the end of the <body> tag
        console.log( "three", getFoo() ); // "foo"
        console.log("three",  getAnchor() ); // array with one element
    </script>

    <script>
        // reference: FOUR
        $(document).ready(function(){
            // call your function inside the jQuery 'ready' event
            console.log( "four", getFoo() ); // "foo"
            console.log( "four", getAnchor() ); // array with one element
        });
    </script>
</body>
</html>

The function getFoo doesn't need the DOM to work. So, its 4 calls always returns 'foo', so the function works wherever and whenever she was called (inside or outside the 'ready' event).

The function getAnchor query the DOM and return a collection of the anchor tag in the page. The first call, in the script "ONE", is outside the ready event and returns undefined. The third call, in the script "THREE", is also outside the ready event but it logs an array of anchor elements in the console. This means that, the placement of the function call can alter the function behavior . In the first call, obviously the anchor tag was not present in the page, and that's why the function returns undefined . Then, the second call and fourth call, placed at the beginning and at the end of the page, both logs an array. In this case, the placement of the function call doesn't alter the function behavior, because the function getAnchor is actually called after all the DOM elements have been loaded. If you look at your console logs, you'l see something like this:

one foo
one []

three foo
three [<a href=​"www.example.com">​bar​</a>​]

two foo
two [<a href=​"www.example.com">​bar​</a>​]

four foo
four [<a href=​"www.example.com">​bar​</a>​]

Look at the log order: one, three, two, four; which is different from the source order: one, two, three, four. Functions is the ready have been delayed until the page loading is complete.

sure - you can write your functions any where you want. They don't need to be in your document ready function at all. I don't like to clutter it with functions so I just write them outside. There is no real reason that you should or shouldn't ; The functions should work anyway.

The idea is that those functions will only be called from within your $(function(){}); (document.ready function).

The document ready function is called once all the HTML elements (aka the DOM) is fully loaded and also jQuery is ready. A best practice (IMO) is to load your jQuery file last - after all your custom JavaScript files and css files. That way, only once the document ready function is called - you are 100% certain that all your files are loaded and ready.

<head>
  <link type="text/css" href="myStyle.css">
  <script type="text/javascript" src="myFunctions.js" ></script>
  <script type="text/javascript" src="myUtils.js" ></script>
  <script type="text/javascript" src="jquery-1.7.2.min.js" ></script>
</head>

You can even place your functions in a separate file altogether... As long as you don't call the function before all its dependencies are met you should be fine.


re: your edit -

Once the document ready function is called - you are able to use jQuery methods anywhere within your JavaScript. If your AJAX call happens before your document is ready, it probably won't know how to actually execute the request (if you are using a jQery AJAX call). You'll have to call that function from within your document ready. Just replace the "on page load" event with the callback to document ready - make it load new messages once jQuery is ready.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM