2014-01-14 26 views
0

下面給出的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(); 
    }); 
}); 

回答

1

我只是刪除了DOM就緒支架,所以它會很快被瀏覽器解析執行爲,請務必先解析要選擇的元素(腳本必須在元素之後)

$(".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(); 
}); 
+0

'$(文件)。就緒(function()...'等待DOM準備就緒,當執行代碼時,引用的DOM元素有可能不存在。 –

+0

我做了一點更新 –

+0

這個更新是正確的,但是你的代碼示例是HTML編碼... –

2

您可以在渲染出它所影響的元素後直接加載它。

例如

<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> 
0

頁面上的內容一經分析就會呈現。

所以爲了讓它儘快渲染,把它作爲第一個元素在< 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 

請注意,渲染時間和執行時間是不相同。

該代碼會盡快在頁面開始加載渲染,但只有當DOM準備將執行(因爲這是你要求它做的事:

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

如果您在標頭中運行代碼,那麼JavaScript引用的DOM元素將不可用,除了您仍然調用$(document).ready(...),這意味着代碼仍然不會運行直到整個DOM可用。 –

+0

請檢查添加的文本 – user1853181

相關問題