视频嵌入和缩略图不会在首次访问页面时加载

时间:2019-07-27 17:16:38

标签: javascript html reactjs embed

我已经将一些youtube视频嵌入到我的网站中。刷新页面后,视频加载并显示正常,但是在首次访问时,它们仅显示为黑框。这是我在index.html文件中使用的脚本,一旦渲染了React组件,便用缩略图和iframe替换了我的divs

index.html

       let youtube = document.querySelectorAll(".youtube");
    //now iterate through the selected items
    for (let i = 0; i < youtube.length; i++) {
      //thumbnail image source
      let source = "https://img.youtube.com/vi/"+ youtube[i].dataset.embed + "/sddefault.jpg";

      //load the image asynchronously
      let image = new Image();
        image.src = source;
        image.addEventListener("load", function() {
          youtube[i].appendChild(image);
        }.bind(this,i) );

      //attach click event to div and create iframe for it
      youtube[i].addEventListener( "click", function() {
        var iframe = document.createElement("iframe");

          iframe.setAttribute("frameborder", "0");
          iframe.setAttribute("allowfullscreen", "");
          iframe.setAttribute("src", "https://www.youtube.com/embed/" + 
 this.dataset.embed + "?rel=0&showinfo=0&autoplay=1" );
          this.innerHTML = "";
          this.appendChild(iframe);
      })
    }

包含视频标记的反应组件:

<ArticleConsumer>
  {(stories) => {
       return stories.sports.map((story) => {
         var VIDEO_ID = story.videoPath.substring(32);
         var shortDate = story.date.substring(0, 10);
         return (
            /* Video wrapper */
            <div className="youtube" data-embed={VIDEO_ID}>
              {/* the play button */}
              <div className="play-button"></div>
            </div>
          )
        })
    }}
</ArticleConsumer>

再一次,刷新页面后,视频会加载并恢复正常,但在初次访问页面时不会加载。我一直在努力找出原因

0 个答案:

没有答案