How to Add a Script Tag in a Vue Component

Gaute Meek Olsen
2 min readNov 15, 2018

--

Update: for Vue 3 check out my updated article on https://gaute.dev/dev-blog/script-in-vue

You might stumble upon an error if you would like to run a script tag only on a specific component in Vue.

Let's try to add a script into a component template:

<script src="..." ></script>

Building this, Vue throws the error: “Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as script, as they will not be parsed.

This is an easy fix, despite googling internet might send you down a harder path. Just add type=”application/javascript” to your script tag. Fixed.

<script type="application/javascript" src="..."></script>

You could stop reading here. But what if your script contains document.write. Your script won’t work and throw this error in the console: “Failed to execute ‘write’ on ‘Document’: It isn’t possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

This happens because the document has been fully parsed and closed. Then you can’t write to it, at least not how you want to.

This can be solved using postscribe. (see hyperlink for other approaches than NPM install)

npm i postscribe --save

Then in the mounted lifecycle to the Vue component, you can add the script tag like this.

<template>
<div id="gist"></div>
</template>
<script>
/* eslint-disable no-useless-escape */
import postscribe from 'postscribe'export default {
name: 'Gist-Example',
mounted: function () {
postscribe('#gist', `<script src="https://gist.github.com/gautemo/d6b309c2bafe8f611f239b82f4f5501f.js"><\/script>`)
}
}
</script>

Congratulations, you now have embedded a gist in your Vue component!

Thank you for reading!

Feel free to follow me on Twitter at @GauteMeekOlsen

This article was originally published on gaute.dev

--

--