简体   繁体   中英

$(document).ready can't replace js declared at bottom of the page, but I need to have the script at the top

I have JQuery based tab navigation that only works if it is placed after the html for the menu. It works if it's placed at the end too, but breaks when I put the same script in $(document).ready ath the top.

I thought that this (placed at the top of the page):

<script type="text/javascript">
$(document).ready(function(){
    mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
});
</script>

would be the same as this:

    <script type="text/javascript">
        mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
    </script>
</html>

Which is placed at the bottom of the page and works. How would I be able to put the function at the top or even include it from a separate file?

I had this problem and I had used this in the head after the jquery include link:

$(document).ready(myfunction());

This failed due to objects not being loaded. I should have wrapped my call in a function:

$(document).ready(function () {
    myfunction();
});

This worked as expected only after the document was properly loaded.

The reason it is recommended to place the script at the end of the page , is so that the HTML elements are loaded onto the page before you try to access them..

No matter where you place the code it is better to wrap in DOM ready event which makes sure the complete HTML document is properly loaded before you try to access the elements in the page..

Maybe in your case

 <script type="text/javascript">
        mouseovertabsmenu.init("mytabsmenu", "mysubmenuarea", true);
    </script>

seems to be working when not encased in DOM ready is the function is not accessible as it's scope is being blocked by DOM 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