Search code examples
javascriptjqueryhtmlboilerplate

Requiring JS files at bottom of document presents usability issues


This is more of a best practice question.

I recently began using the HTML5 boilerplate for a bunch of projects I have been doing but recently discovered something that could be an issue. Another developer brought to my attention that it may be an issue loading JS files at the bottom of the document due to certain functionality not working on page load( ie. form using jQuery $.ajax) and in turn presenting some usability issues. I wanted to get some opinions on what is the best way to address common issues like this that may arise. I have been using HTML5 boilerplate as I know Paul Irish and friends have really thought out this system and are constantly improving upon it.

Example issue: Home page of site has newsletter sign up form that uses the jQuery $.post function to submit values of form. User has access to enter values and press submit but this will render no action as js is not loaded presenting usability issues.

What is the best way to work with JS included at the bottom of the site?


Solution

  • My recommendation would be this:

    • put all your SCRIPT elements at the bottom of the page
    • let the jQuery script be in the first SCRIPT element
    • let the second SCRIPT element contain a ready() handler for the behavior that you want to become available as soon as possible

    Like so:

    <script src="http://ajax.googleapis.com/.../jquery.min.js"></script>  
    <script>
        $(function() {
            // bind the handler to the newsletter submit button
            // etc.
        });
    </script>
    <!-- all other external and inline scripts should be below this line -->
    <script src="pluginA.js"></script>
    <script src="pluginB.js"></script>
    <script>
        $(function() {
            // other page load code
        });
    </script>
    

    This is the best you can do.

    Btw, users expect the page to be broken for the first couple of seconds anyway. I experience this all the time on Facebook, Youtube, ...