Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put my JavaScript code?

I would like to use the code for the auto-complete. The code is here.

<script>
    $(function() {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"
        ];
        $( "#tags" ).autocomplete({
            source: availableTags
        });
    });
    </script>



<div class="demo">

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags">
</div>

</div><!-- End demo -->



<div class="demo-description" style="display: none; ">
<p>The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are tags for programming languages, give "ja" (for Java or JavaScript) a try.</p>
<p>The datasource is a simple JavaScript array, provided to the widget using the source-option.</p>
</div><!-- End demo-description -->

However, I cannot figure out where I should put this code. In head? In body?

like image 616
Roman Avatar asked Jan 10 '11 14:01

Roman


2 Answers

According to w3schools

When to put script in HEAD

Scripts to be executed when they are called, or when an event is triggered, are placed in functions. Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

When to put script in BODY

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

So in your case. You can put the script in the body

like image 92
Shervin Asgari Avatar answered Oct 05 '22 17:10

Shervin Asgari


You should probably put your code right at the end of the body tag.

Check out Steve Souder's High Performance Web Sites - Evolution of Script Loading

If you have multiple script includes and need to convince yourself that they will load in the correct order for you, check out WebSiteOptimization.com's Article on the Defer Attribute, where you can see the order your scripts execute.

like image 44
Yoh Suzuki Avatar answered Oct 05 '22 17:10

Yoh Suzuki