为什么javascript(fluidvids.js)只能在视频嵌入后加载时工作

Why is a javascript (fluidvids.js) only working when loaded *after* a video embed?

本文关键字:视频 加载 工作 javascript fluidvids js 为什么      更新时间:2023-09-26

当fluidvids.js代码在视频嵌入之前插入时,我无法让fluidsvids.js在我的github页面托管网站上运行(在Poole/Jekyll上运行)。

然而,当在视频嵌入之后插入代码时,由于fluidvids.js,视频会根据布局调整大小。为什么


我将整个fluidvids zip文件提取到/public/js/fluidvids中。

在我的_includes文件夹中,我创建了一个html文件fluidvids.html:

<!-- fluidvids.js -->
<script src="{{ site.baseurl }}public/js/fluidvids/dist/fluidvids.js"></script>
<script>
fluidvids.init({
  selector: ['iframe'],
  players: ['www.youtube.com', 'player.vimeo.com']
});
</script>

在我的default.html布局中,我插入了{% include fluidvids.html %}:

<!DOCTYPE html>
<html lang="en-us">
  {% include head.html %}
  {% include google_analytics.html %}
  <body>
    {% include fluidvids.html %}
    {% include sidebar.html %}
    <div class="content container">
      {{ content }}
    </div>
  </body>
</html>

最后,我在帖子中嵌入了两个测试视频;2007-02-10-Island-of-Lost-Souls.md:

<iframe src="https://player.vimeo.com/video/9685584" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe width="420" height="315" src="https://www.youtube.com/embed/ZdyzjKDWpYU" frameborder="0" allowfullscreen></iframe>

然而,直到我将include放在博客文章内容之后,视频才随着布局调整大小,如下所示:

<!DOCTYPE html>
<html lang="en-us">
  {% include head.html %}
  {% include google_analytics.html %}
  <body>
    {% include sidebar.html %}
    <div class="content container">
      {{ content }}
      {% include fluidvids.html %}
    </div>
  </body>
</html>

为什么

当fluidvid.js在博客文章内容之后加载时,这是渲染的帖子。

因为在调用fluidvids.init之前,您没有等待文档就绪(onload)。如果脚本块在视频元素之前,您需要等待文档加载事件,否则初始化将(静默?)失败,因为浏览器还没有机会处理其标记,所以选择器不会返回任何元素。因此,要么绑定到onload事件,然后运行fluidvids初始化,要么在有问题的元素之后包含脚本块。

顺便说一句,最佳实践表明脚本块将包含在body元素的末尾。