jquery加载时间和里面的css样式

jquery load time and css styling inside it

本文关键字:css 样式 加载 时间 jquery      更新时间:2023-09-26

正如您在下面的代码中看到的,jquery加载了一个页面,但jquery中的所有.css样式似乎都在等待,直到加载jquery,如果文件很大,这可能需要几分之一秒的时间。因此,如果我有.css("display","none"),它在样式开始之前不会工作,导致闪烁。我只有Mozilla有这个问题下面的代码只是一个示例,它运行良好,因为它很小。一些如何解决的想法?

$(document).ready(function() {
  $(".rectangle").click(function() {
		$("body").load("debugging2.html", function() {				
            $(".rectangle").css("display","none")
				    $(".rectangle").fadeIn(1000);										
		 })	;								
   });
})
.rectangle{
		height: 200px;
		width: 200px;
		background-color:#000;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
  <div>  
    <div class="rectangle"></div>
  </div> 
</body>

$(document).ready(function() {
    $(".rectangle").click(function() {
        $("head").append("<style>.rectangle{display:none;}</style>");
        $("body").load("debugging2.html", function() {      
           $("rectangle").fadeIn(1000);                                     
        });                             
    });
})

由于脚本标记是同步加载的(默认情况下),因此它们确实会阻止页面呈现。如果HTML没有被处理并且样式在那个时刻没有被加载,它可能会导致空白的无样式页面。因此,常见的非常简单的解决方案是将沉重的脚本标记移动到</body>的末尾,并在<head>中放置必要的CSS样式。

如上所述,CSS首先被下载,在HTML被快速加载、渲染和样式化之后,只有在缓慢的脚本被下载之后。

在代码中,它看起来像这样:

<head>
  <link href="style.css" rel="text/css" type="stylesheet">
</head>
<body>
  <div>  
    <div class="rectangle"></div>
  </div> 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <!-- some other scripts -->
</body>

额外的好处是,您不需要再绑定到文档就绪事件($(document).ready(function() {});),因为在执行脚本时,HTML都是默认加载的。