简体   繁体   English

如何使$(document).ready(function()JavaScript尽快渲染?

[英]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. 下面给出的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();
    });
});

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) 我刚刚移除了dom-ready括号,因此它将在浏览器解析后立即执行,请确保您要选择的元素在解析之前(脚本必须在元素之后)

$(".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: 因此,为了使其尽快呈现,请将其作为<head>标记中的第一个元素,如下所示:

<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: 此代码将在页面开始加载后立即呈现,但仅在DOM准备就绪时才会执行(因为这就是您要求它执行的操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM