解决以防止看到文档就绪 javascript 更改

Work around to prevent seeing doc ready javascript changes

我正在努力深入了解为什么会看到以下内容,以及如何解决它:

我在下面链接了一个测试页面,它的 DOM 非常小,我在页面上有一个元素的初始高度值完全由 CSS 设置,在文档准备就绪时,一个jQuery 函数触发,为该元素分配一个新的高度值,我的问题是当页面构建时,这种变化在视觉上很明显,您可以看到元素快速从 jQuery 获得新的高度值功能,我的目标是防止这种情况发生,因此当页面加载时,您只会看到具有 jQuery 高度值的元素。我认为 JavaScript 呈现会阻止页面在浏览器中构建,直到所有文档就绪功能都已触发,除非已设置异步或延迟,但现在我假设我错了。

编辑:

澄清一下,这只是一个例子,我要解决的问题与身高无关,我正在尝试解决我的 jQuery 在 doc ready 上应用 CSS,更好地理解延迟存在的原因。

The test page link

整个DOM:

 <style>
  html {
      background: #eee;
  }
  .box {
      height: 64px;
      width: 50%;
      max-width: 280px;
      max-width: 1280px;
      margin: 64px auto 0 auto;
      position: relative;
      background: #fff;
      box-shadow: 0 0.08em 0.25em 0 rgba(0,0,0,0.3);
  }    
</style>

<script type='text/javascript' src='[my path]/js/jquery-3.1.1.min.js?ver=3.1.1'></script>

<script type="text/javascript">
  jQuery(document).ready(function(){       
      function adjustBox() {
          windowHeight = window.document.documentElement.clientHeight;
          $('.box').css('height', windowHeight * 1/2);
      }   
      adjustBox();     
  });     
</script>

<div class="box"></div>

如果你想要那个盒子 50% 的用户 window 高度,你可以用 CSS:

.box {
    height: 50vh; // vh => view-height
}

您的示例 JavaScript 在 DOM 加载后执行。 这就是为什么您会在页面加载后看到 .box 高度调整大小的原因。 当您将 <script> 标记放在 <head> 中并且不使用 jQuery.ready() 函数时,您可以在页面完全加载之前 运行 JS。

 <head>
    <script>
       // 1
       alert('this runs immediately. even before the document has been parsed');

       // 2
       $(function() {
           alert('this runs when the document has been loaded');
       });

       // 2
       $(document).ready(function(){
            alert('this runs when the document has been loaded');
       });

       // 3
       $(window).load(function(){
            alert('this runs when the document has been loaded AND resources like images has been loaded');
       });
    </script>
</head>
<body>
    <script>
        // 2
        alert('this runs when the document has been loaded');
    </script>
</body>
  • 评论1:JS 无法操作此处的文档,因为它尚未加载。您可以进行重定向或从服务器加载数据等。
  • 评论2:这些基本上是一样的。该文档已准备好由 JS 操作。但这并不意味着所有资源都是 加载。您无法获得图像的准确高度。
  • 评论 3:如果您需要获取想要使用的图像的高度 $(window).load

您可以执行类似于 vue/angular/etc... 的操作,并有一个可以应用于 "hide" 元素的辅助属性,直到它被完全处理。

css

html {
  background: #eee;
}
[data-cloak] {
  display: none !important;
}
.box {
  height: 64px;
  width: 50%;
  max-width: 280px;
  max-width: 1280px;
  margin: 64px auto 0 auto;
  position: relative;
  background: #fff;
  box-shadow: 0 0.08em 0.25em 0 rgba(0,0,0,0.3);
}

js

jQuery(document).ready(function(){       
  function adjustBox() {
    windowHeight = window.document.documentElement.clientHeight;
    $('.box')
      .removeAttr('data-cloak')
      .css('height', windowHeight * 1/2);
  }   
  adjustBox();     
});

JSFiddle example