$(document).ready 或 window.onload 用于 hiding/showing 个视频

$(document).ready or window.onload for hiding/showing a video

我是 运行 一个脚本(hack),用于诱骗 Safari 在响应页面上正确调整视频大小。下面的脚本稍等片刻,然后隐藏,然后显示一个视频,使 Safari 意识到它应该将视频扩展到适当的大小。

我担心 $(document).ready 可能会过早触发脚本(即在视频加载之前),从而导致脚本无法对视频执行应有的操作。是否有可能 $(document).ready 脚本可能会触发,但由于视频在设定的毫秒数后未加载,因此视频不会 hidden/shown?

我是否应该使用 window.onload(或其他方法?)来确保我的 hide/show 大小调整有效?

在我的测试中,脚本大部分都有效,即使在我清除缓存时重新加载也是如此。但是有几次,当我在随机计算机上加载页面时,在我重新加载页面之前,视频的大小不会正确。使用 window.onload 似乎不太理想,因为用户可能会在加载页面内容时注意到视频大小不正确,或者在加载后看到黑客正在运行。

<script><!-- Super hack to toggle display block/none which tricks Safari into properly sizing video-->
    $(document).ready(function() {
    $("#video1").delay(3000).hide(0, function() {
        $("#video1").delay(3500).show();
        });  
        });
 </script>

这是两个事件之间的区别:

  • window.onload 在所有内容(即媒体和样式表)加载后触发。这是一个DOM事件

  • $(document).ready() is fired after the HTML document has loaded (i.e the very last closing tag has been loaded, the media and stylesheets may not have loaded yet). This event is technically unique to jQuery but, if aailiabe, jQuery actually uses the DOMContentLoaded DOM 事件。

但是,jQuery 确实有一个仅在所有媒体加载后才触发的事件,$(document).load(),但是自 1.8

起已弃用

如果您希望您的代码 运行 视频加载之前,请使用 $(document).ready()

如果您希望代码在运行 视频加载后,请使用window.onload$(document).load()


回答您的评论:

Provided the video has loaded by the time the delay have finished (totals to 7.5 seconds), your hack will work.

Even if the video has not loaded, the HTML element still exists, so it can be hidden and shown even before the video has loaded (though I am not sure if the hack will still work, it depends on how and when Safari decides the size of the video).

Obviously if the video hasn't loaded, hiding and showing will not alter anything visually, since the element is empty / has no content.