Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...