简体   繁体   English

通过 DOM 插入 JS 播放器失败

[英]Inserting JS player through DOM fails

I have used JavaScript media players in the past, mostly Video.js .我过去使用过 JavaScript 媒体播放器,主要是Video.js Commonly, to get a video player on a page I would use this:通常,要在页面上获取视频播放器,我会使用以下命令:

<link href="https://unpkg.com/video.js/dist/video-js.min.css" rel="stylesheet">
<script src="https://vjs.zencdn.net/7.7.6/video.js"></script>           
<video id="my-video" class="video-js vjs-16-9" ...>
    <source src="https://.../video.m3u8" type="application/x-mpegURL"/>
</video>

I now have a situation where a JavaScript function first needs to run on my page to identify what media URL should be played.我现在遇到的情况是,首先需要在我的页面上运行 JavaScript 函数来确定应该播放哪个媒体 URL。 I make a call to the API, and when it returns, I try the following:我调用 API,当它返回时,我尝试以下操作:

const app = document.getElementById('root')
var embedContents = "<link href=\"https://unpkg.com/video.js/dist/video-js.min.css\" rel=\"stylesheet\">"
embedContents = embedContents + "<script src=\"https://vjs.zencdn.net/7.7.6/video.js\"></script>"
embedContents = embedContents + "<video id=\"my-video\" class=\"video-js vjs-16-9\" ...><source src=\""
embedContents = embedContents + myURL
embedContents = embedContents + "\" type=\"application/x-mpegURL\"/></video>"
    
const embed = document.createElement('div')
embed.innerHTML = embedContents
app.appendChild(embed)

Forgive me if this is not the right way, I'm pretty new to JavaScript.如果这不是正确的方法,请原谅我,我对 JavaScript 还很陌生。 Once this runs, all I get is a black box on the page, the player doesn't actually load.一旦运行,我得到的只是页面上的一个黑框,播放器实际上并没有加载。 From the debugging I've done, it appears that the scripts are being fetched.从我完成的调试来看,似乎正在获取脚本。 I've also tried putting the link and script tags in the <head> of my HTML file.我还尝试将linkscript标签放在我的 HTML 文件的<head>中。

I needed to import the script in a more specific way, like so:我需要以更具体的方式导入脚本,如下所示:

var script = document.createElement('script');
script.src = "https://vjs.zencdn.net/7.7.6/video.js"
app.appendChild(firstScript)

Then I used the rest of the div element as before.然后我像以前一样使用了div元素的其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM