What is the process of embedding a Vue.js application into an already existing webpage using script tags?

My goal is to integrate a Vue.js application into an existing webpage using script tags. Upon running `npm run build` in my Vue application, I end up with 7 compiled files:

  1. app.js
  2. app.js.map
  3. manifest.js
  4. manifest.js.map
  5. vendor.js
  6. vendor.js.map
  7. app.css

Initially, I attempted to load the three main js files (manifest, vendor, and app - excluding the map files) as sources within script tags on a separate webpage in hopes of having the Vue application display on that page.

(Although not currently concerned about it, the css file would also be loaded onto the page.)

However, even after inserting the js files as sources in script tags, the Vue application does not appear to be 'executed' and there are no DOM elements present on the page from the Vue application.

In addition to loading the three main js files, I've also included the vue.js (development version) js file via a script tag on the page.

While I am not well-versed in web-pack, it seems like there may be a step required to prompt webpack to execute the Vue application on this separate webpage, considering webpack is used for local execution of the Vue application.

I'm uncertain if what I am attempting is feasible and have been unable to locate any resources illustrating how to achieve this integration.

If possible, please share any relevant guidance or information regarding whether this method is correct for running a Vue application within a third-party webpage.

EDIT

Here is the JavaScript code utilized to insert the script tags with the src of the files:

var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.src = "/js/app.js";
head.appendChild(js);

The above code snippet is repeated for each of the files (app, manifest, and vendor). This is the extent of my implementation, where the script tags exist on the page with the corresponding sources. In Chrome debugger's sources tab, all three js files are seen being appropriately loaded.

Answer №1

SOLUTION

I had trouble getting my Vue app to load in another application because the Vue js files required a specific div element with the id of "app" to initialize properly. Below is the snippet of code I used, with some general values substituted, in a JavaScript file within the target application:

var head = document.getElementsByTagName('head')[0];
var body = document.getElementsByTagName('body')[0];

var div = document.createElement("div");
div.id = "app"
body.appendChild(div)

var js = document.createElement("script");
js.src = "/js/vue-app.js";
js.id = "vue-app-js";
js.defer = true;
js.async = true;
head.appendChild(js);

var css = document.createElement('link');
css.id = "vue-app-css";
css.rel = "stylesheet";
css.type = "text/css";
css.href = "app.css";
head.appendChild(css); 

To streamline the process, I consolidated all the compiled Vue js files (manifest, vendor, and app) into a single file named vue-app.js as shown above. Once these files are successfully loaded on the page, they work together to construct the Vue js application within the designated div element identified by its id as "app".

Answer №2

Avoid including Vue in your index.html file directly; it should be part of the vendors bundle. Consider using this plugin to automate the generation of your index.html.

If you're utilizing webpack with official vue-cli templates, they are designed to help navigate and resolve such issues effectively.

Answer №3

My intention is to avoid referencing the Vue js files in the Vue index.html file and instead utilize them on a separate website through script tags. The Vue app functions correctly when locally run in its designated environment. I am currently employing the official webpack via vue-cli for this purpose. While unsure if it is feasible to integrate a Vue app into a different website using only js script tags, I am open to exploring potential solutions.

Unfortunately, the desired method of incorporating a Vue app into a separate website solely through script tags may not be achievable in the manner expected. However, another option could involve embedding the Vue.js site within an <iframe> on the alternative website.

Answer №4

James's approach is perfect for integrating with vue3, here is the customized version I implemented to load multiple files - app.js, chunk-vendors, and some asynchronous chunks

  // Convenient function to dynamically insert a script tag into the DOM
  const insertScript = src => {
    const element = document.createElement("script");
    element.src = src;
    element.defer = true;
    element.async = true;
    document.body.appendChild(element); // Ensuring compatibility with production built index.html
  };

  // Create a div element with an id corresponding to main.js/main.ts
  const container = document.createElement("div");
  container.id = "app";

  // Invoke insertScript for each script url in the array
  // The array is not defined here but it should consist of 
  // string elements representing individual script URLs
  scriptUrls.map(insertScript);

I have not incorporated any styles, but James's solution for styling should yield satisfactory results.

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

How to Incorporate an Error Function into XPages Partial Refresh Events (dojo.xhrPost)?

I have a page that relies on multiple partial refreshes for user interaction. Rather than implementing a session keep alive mechanism, I am interested in detecting error responses from these partial refreshes to alert the user of their expired session or t ...

ReactiveJS - Adding elements to an array and encountering the error of undefined

In two separate JavaScript files, I have 2 arrays declared as shown below: Index.JS: const [product, setProduct] = useState([]); const [item] = useState([ { name: 'Blue Dress', Image: '/static/media/Dress.1c414114.png', Pr ...

Encountering an issue while attempting to access a JSON file using the fetch method

When attempting to read a json file locally, I encountered an error that looks like this: Fetch API cannot load file:///var/www/desktop-electron//dashboard/bnb.json. URL scheme "file" is not supported Below is the code snippet being used: fetch(`${drr}/ ...

The body in Express is set to "Cannot GET [route]" during the execution of asynchronous code

I am currently working on an express application that includes some articles stored in a Mongo database. As I wait for the mongoose model Article to load, the body of the request gets changed to: <!DOCTYPE html> <html lang="en"> < ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Utilizing JavaScript to implement a single method across multiple objects

Recently, I encountered a problem while trying to use the prototype method to apply the same function or variable to multiple objects. Despite creating numerous objects in the following manner: var item = { a: { aa: "lalala", ab: 1, somethin ...

The elements being parsed are appearing as undefined

Currently, I am attempting to analyze this JSON structure: { "customers": [ { "name":"joe" , "cars":[ {"name":"honda","visits":[ {"date":"01/30/14","Id":"201"}, {"date":"01/30/14","Id":"201"}, {"date":"02/12/14","Id":"109"} ...

The program encountered an issue: Initialization must be completed before utilizing hooks

I'm facing an issue with my new Next app. I added line no. 6 and now I'm getting an error. Can anyone help me understand why? https://i.sstatic.net/lMKH5.png import Head from "next/head"; import Image from "next/image"; impor ...

Using the Trigger Method in a Vue JS Component with Sibling Components

Seeking assistance once again for a VueJS2 project. Currently, I have a setup with a parent component, along with child1 and child2. The scenario is that the form in child1 needs to receive data from child2, which acts as a table. When a checkbox on a row ...

A guide to fetching a JSON Object from a URL using Node.js and Express

As a newcomer to Node.js and Express, I am venturing into my first real project with these technologies. In this simple Node.js/Express project, my goal is to retrieve a JSON object from a URL. Additionally, I plan to create another URL that shows HTML co ...

serving index.html using express and react

I am currently working on an application with Express, which includes a create-react-app. My goal is to display the index.html file located in the public folder of the create-react-app when a user visits the root URL. Below is the code snippet from my inde ...

Having trouble implementing a transition on a dropdown menu in React

Can anyone help me troubleshoot an issue with adding a transition to a select box that appears when clicking on an input field arrow? I have tried implementing a CSS transition property, but it doesn't seem to be working. Any suggestions on what might ...

Showing text on an ajax loader

While making an ajax call, I have implemented functions that are called on success. To enhance user experience, I am displaying a spinner during the call and hiding it once completed. My goal is to show a message along with the spinner to indicate which fu ...

The entire Sphere Geometry in three.js is not completely encompassed by the texture

Click here to view the image I'm trying to create a rotating moon. Everything works perfectly with MeshStandardMaterial (with color but no texture), however, when I apply a texture to the sphere geometry, it behaves strangely. The issue I'm facin ...

Preventing FlatList from scrolling when re-sizing

Resizable from the re-resizable package is causing my Flatlist not to scroll properly. Despite having enough elements to trigger scrolling, it fails to do so when the resizable element is present. This issue does not occur when the resizable element is rem ...

Having difficulty managing asynchronous Node JS API requests

I'm a beginner in Node.js and I've taken on a project that involves querying both the Factual API and Google Maps API. As I put together code from various sources, it's starting to get messy with callbacks. Currently, I'm facing an issu ...

Using the https module in Node.js to transfer a file to a PHP server

What is the best method to send an HTTP post request that includes a jpg file to a php server using the node https module? I attempted to use the request module, but it is unreliable (timing out most of the time) and already deprecated. Here is the functi ...

How to correct header alignment in HTML for Google Table

Utilizing the google visualization table to generate a html table, I have successfully fixed the top section of the html using the stuckpart div. This ensures that regardless of how I scroll, the button remains in place. However, I now aim to fix the table ...

Retrieve the HTML contents of a cell that contains a checkbox with the value of "jquery"

Here is an example of a table row: <tr> <td><input type='checkbox' name='post[]' value="1"></td> <td>08-Apr-2014</td> <td>injj team</td> <td>merchant.testyy.com</ ...

Swap out ASP.NET AJAX with jQuery for making ASHX requests

Recently, I have been utilizing the following method to communicate with a Web Proxy for cross domain calls. However, as I am in the process of updating my code and already use jQuery, I am considering dropping ASP AJAX since it is only used for this speci ...