How to include a <script> tag on a Vue component

When trying to insert a script tag into the <template> tag of a Vue component the following error is emitted.

- 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.

One could ask, why would you event want to include a <script> tag inside a template in Vue. The reason why I stumbled into it was to load an external script only on specific pages.

If you want to include an external script that you think will be used on every page it is easy. Just add the <script> tag to index.html and it will be downloaded.

However, some scripts might be quite large and you don’t want to download them for all users, if they’re only used in some specific situations.

One way to solve this is to programmatically create the script tag and add it to the DOM. The following code snippet creates the element, adds the source attribute for the script and appends it to the DOM. All of this is done during the created lifecycle hook.

created() {
let ckeditor = document.createElement('script'); ckeditor.setAttribute('src',"//");

Do you know any other way to download an external script with Vue? Let me know if there’s an even better way to do it!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store