[英]How to make a $(document).ready(function () JavaScript render 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();
});
});
在渲染出影响的元素之后,可以直接加载它。
例如
<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>
我刚刚移除了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();
});
页面上的内容在解析后立即呈现。
因此,为了使其尽快呈现,请将其作为<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 () { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.