Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs 2: How to include (and run) a script tag javascript file in the DOM dynamically?

Tags:

I am using Vuejs and I need to insert script tags in the DOM dynaically to embed JWPlayer videos in this way:

<body>
 <!-- HTML content -->
 <script src="//content.jwplatform.com/players/KZVKrkFS-RcvCLj33.js"></script>
 <!-- More HTML content -->
 <script src="//content.jwplatform.com/players/ANOTHER-ID-ANOTHER-PLAYERID.js"></script>
</body>

I have used without results: v-html directive to render the html tags. As well v-bind:src but neither execute the code. I found this solution but it did not work either: How to add external JS scripts to VueJS Components

I used this solution but the script tags (one for each video) must be inserted in the body (not in head): they should create div tags containers and embed the videos. The problem is that the embeded JWPlayer file contains a document.write() statement. And the browser console says: "A call to document.write() from an asynchronously-loaded external script was ignored."

Is there anyway to achieve this?

like image 955
Spleen- Avatar asked Dec 12 '17 08:12

Spleen-


People also ask

How do you add a script tag to Vue?

Add a script tag inside your Vue component template. Just add the script into the component template. But don't forget to add, type="application/javascript" to the script tag otherwise it will show an error during the build.

How do I add external js scripts to Vuejs components?

To bring 3rd party script into a @vuejs Vue3 component, then do logic on code brought in by that script, I did this: In setup function, createElement/setAttribute with script url. Then setInterval/clearInterval to check that it's there, do logic if it is.

Can we add script tag in js file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can you put the script element inside the body?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.


1 Answers

The link you provided should work.

You probably just need to wait for the script to load before you can use JWPlayer.

const script = document.createElement('script')

script.onload = () => {
  // Now you can use JWPlayer in here
}

script.src = '//content.jwplatform.com/players/MEDIAID-PLAYERID.js'
document.head.appendChild(script)

Also make sure you only do this one time for the first component that requires it, from that point onward JWPlayer will be loaded and you can use it without inserting another script tag.

like image 114
Decade Moon Avatar answered Oct 15 '22 09:10

Decade Moon