简体   繁体   中英

How to make a $(document).ready(function () JavaScript render as soon as Possible?

Below given JavaScript is rendering at End, When Whole page is Fully Loaded, But I want to render it as soon as Possible without affecting it's Natural working, Can any one modify this such that it renders as soon as Possible.

$(document).ready(function () {
    $(".tab_content").hide();
    $(".tab_content:first").show();

    $("ul.tabs li").click(function () {
        $("ul.tabs li").removeClass("active");
        $(this).addClass("active");
        $(".tab_content").hide();
        var activeTab = $(this).attr("rel");
        $("#" + activeTab).fadeIn();
    });
});

You can load this directly after you've rendered out the elements that it affects.

eg

<ul class="tabs">
   ...all your tabs
</ul>
<script>
  $(".tab_content").hide();
  $(".tab_content:first").show();

  $("ul.tabs li").click(function () {
    $("ul.tabs li").removeClass("active");
    $(this).addClass("active");
    $(".tab_content").hide();
    var activeTab = $(this).attr("rel");
    $("#" + activeTab).fadeIn();
  });
</script>

i just removed the dom-ready brackets, so it will be executed as soon as its parsed by browser, be sure the elements you want to select are parsed before ( script must come after elements)

$(".tab_content").hide();
$(".tab_content:first").show();

$("ul.tabs li").click(function () {
    $("ul.tabs li").removeClass("active");
    $(this).addClass("active");
    $(".tab_content").hide();
    var activeTab = $(this).attr("rel");
    $("#" + activeTab).fadeIn();
});

Content on the page renders as soon as it is parsed.

So in order to have it rendered as soon as possible, put it as the first element in the < head > tag, like this:

<html>
<head>
<script type="text/javascript">
    $(document).ready(function () {
        $(".tab_content").hide();
        $(".tab_content:first").show();

        $("ul.tabs li").click(function () {
            $("ul.tabs li").removeClass("active");
            $(this).addClass("active");
            $(".tab_content").hide();
            var activeTab = $(this).attr("rel");
            $("#" + activeTab).fadeIn();
        });
    });
</script>
... rest of the head tag, like meta and title

Please note that rendering time and execution time are not the same.

This code will render as soon as the page has started loading, but will execute only when the DOM is ready (because that's what you asked it to do with:

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

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