Spleen-
Spleen-

Reputation: 73

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

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?

Upvotes: 5

Views: 7429

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

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.

Upvotes: 4

Related Questions