Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

jquery - Will linking javascript files in the body rather than in the header cause a problem?

this is what im trying to do

<script type="text/javascript" src="resources/application.js"></script>
    <script type="text/javascript" >
       $(document).ready(createHeader()); 
       $(document).ready(scriptSet()); 
    </script>

id like to avoid having to separate the two, and while generally i see script links only inside the header the document.ready functions dont seem to work when put there. However, everything seems to work completely fine when placed at the end of the body, so would this cause any problems or is this fine?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Functionally, as long as you enclose your code inside a $(document).ready(function(){ }); and it comes after the jQuery file includes, it does not matter if it's in the head or the body. $(document).ready ensures that the DOM is fully loaded before any script is executed.

HOWEVER, putting all of your script includes and scripts at the bottom of the body is best for loading performance.

This article explains it nicely.

Example:

        <body>

    <!-- MY HTML CODE -->

    <!-- START javascript -->
        <script type="text/javascript" src="/javascript/jquery/jquery-1.6.2.min.js"></script>
        <script type="text/javascript" src="/javascript/jquery/plugins/jquery.random_plugin.js"></script>
        <script type="text/javascript" src="/javascript/jquery/plugins/jquery.random_plugin2.js"></script>
        <script type="text/javascript" src="/javascript/some_other_scripts.js"></script>

        <script type="text/javascript" language="JavaScript">
        //<![CDATA[
            $(document).ready(function(){
                // my code
            });
        //]]>
        </script>
    <!-- END javascript -->

        </body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...