Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue.

My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details:

This is the current setup:

o public
|
|-index.html
|
|-js
| |-script_for_all_pages.js
| |-script_for_index1.js
| |-script_for_index2.js ...

o src (my vue project)

This is what I aim for:

  1. I would like
    <script src="js/script_for_all_pages.js"></script>
    in the HTML of localhost/*
  2. I intend to have
    <script src="js/script_for_index1.js"></script>
    in the HTML of localhost/index1
  3. I plan to include
    <script src="js/script_for_index2.js"></script>
    in the HTML of localhost/index2

So far, I have successfully added the <script> tag to index.html in my public folder. However, I am struggling to execute the last two steps. These routes (localhost/indexx) correspond to components, suggesting that injecting the script into the component index1.vue might be the way to go. Unfortunately, attempts to import it using

import "../js/index.js";
led to multiple errors, and I haven't been able to resolve them.

Here are some packages that failed to deliver results:

vue-inject-js

vue-plugin-load-script

Your assistance is greatly appreciated!

Answer №1

In the world of Vue/React, I have my own method for handling scripts. This handy function can be stored in a helper and easily called from any component upon creation:

public addScript(url, loadAsync=true): HTMLScriptElement {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.async = loadAsync;
    script.src = url;
    document.head.appendChild(script);
    return script;
}

If you're using plain JavaScript, feel free to overlook the types mentioned above. And remember, you can utilize the returned script object to monitor events:

const newScript = addScript("...");
newScript.onLoad = () => {/*take action*/}

It's essential to limit this functionality to external widgets only. If this is your code, there may be a more efficient approach available.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Craft a brief description for every individual component discovered

Is there a way to identify and shorten all elements containing a <tspan> tag to just ten characters each? For example: <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> ...

Guide to setting up Firebase pagination in a NextJS 13 server component

Currently, I am working on developing a product page that showcases all products and functions as a server component. The challenge I am facing is the inability to pass the last visible document snapshot required by the startAfter() query. Below is the fu ...

Ways to adjust text color after clicking on an element

Just a heads up, I didn't write all of the web-page code so I'm not exactly sure what pdiv is. But I want to see if I can fix this small issue [making text color change when clicked on to show which section you're reading]. This particular ...

Ways to develop a dynamic HTML TransferBox featuring a custom attribute

I am in need of developing a customized transferbox using HTML, JavaScript, and JQuery. The user should be able to select from a list of options and associate them with attributes. This selection process should involve transferring the selected options be ...

Add a new division to a component when a specific event handler is triggered by another component using React and the reduce method

Currently, I am developing an interactive drag-and-drop application using React and Redux. My goal is to insert a new div element into a container when the ondragstart event handler is triggered by a component. The component responsible for the dragging o ...

Adding supplementary documents within the app.asar file via electron

This is a Vue application using electron-builder. { "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron:build": "vue-cli-service electron:build", "electron:serve": "vue-cli-service electron:serve", ...

What are the steps for installing the latest version of popper, v2?

When you run the following command: npm install popper.js --save You will receive a warning message that says: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f1eef1f1e4f3afebf2c1b0afb0b7afb0">[email& ...

`Is it possible to remove an empty frame using javascript?`

I have this script that generates a "layer" resembling a frame and I need to remove it. Here is the code for creating the layer: function disableLayer() { var layer = document.getElementsByTagName('div')[0]; d = document.createElement(& ...

kineticjs equivalent to jquery sortable

Could someone recommend a kineticjs plugin or script that works with jquery's "sortable" function? I am trying to create a list of shapes where I can drag and drop them, and when one element moves, the other elements shift into place. ...

What is the best way to handle JSONp response parsing using JavaScript?

I'm relatively new to working with Javascript and I am currently attempting to retrieve data from an External API located on a different website. My goal is to extract the information, parse it, and then display specific parts of it within my HTML pag ...

JavaScript code that displays items in a shopping cart

I've set up the HTML and JS functionality for the cart, but I'm facing an issue where the JS doesn't render the cart items when the shop item is clicked. The styling in my HTML is done using Tailwind. If anyone could provide some assistance ...

What seems to be the issue with this Discord.js kick command code? It's not

Okay, so I'm in the process of creating a kick command for my Discord bot. The issue I'm encountering is that when no reason is specified or if a user is not mentioned to be kicked, the bot responds correctly but does not actually kick the user. ...

Ajax sending numerous requests to the API

Recently, I began my journey of learning Javascript and decided to interact with my Django API through Ajax requests. To achieve this, I created a search bar that triggers the API call after a one-second delay following a keyup action. input.addEventListe ...

Creating a visual comparison by using knockout side by side

I'm currently working on a project that requires me to display multiple items side by side for comparison. The ideal layout would be similar to Amazon's, where each item is represented by a vertical column with all relevant information about tha ...

How can you determine in Chrome when the content of an iframe has been modified by using document.write?

When working with iFrames in different browsers, there can be challenges. For example, in Internet Explorer (IE), we can effectively use the onreadystatechange event to track changes in an iFrame's content when using document.write. However, this meth ...

Exploring the functionality of CodePen's code editor in relation to developing a 2D shooting game

Recently, I created a straightforward 2D shooter game with all the code neatly organized in a single HTML file: (file_gist). When I tested the game in my chrome browser, everything worked flawlessly according to my intentions. However, upon transferring th ...

What is the most efficient way to prevent duplicate items from being added to an array in a Vue 3 shopping cart

I currently have a functional shopping cart system, but I am facing an issue where it creates duplicates in the cart instead of incrementing the quantity. How can I modify it to only increment the item if it already exists in the cart? Also, I would like t ...

applying a timeout for the .on(load) event

My goal is to dynamically load images using .on('load') in the script below: .on('load', function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken i ...

Error occurred while fetching image from Medium story API in Next.js

While working on my Next.js app, I encountered an issue with the Medium story API. Every time I try to fetch and display an image using the API, I receive an error message stating "upstream image response failed." The specific error code is: upstream image ...

Learn the technique of storing a sequence of functions within a variable using jQuery

For instance, I am looking to assign a sequential process to multiple variables and utilize them in various scenarios. var disable_btn = true; var button_me = $('#contents.getsamplekit .sample-form .form #submit-btn-freeSample-me'); var button_d ...