This article is about fixing Uncaught SyntaxError Unexpected token when refreshing page in Vuejs-templates PWA
  • 22-Jan-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing Uncaught SyntaxError Unexpected token when refreshing page in Vuejs-templates PWA

“Uncaught SyntaxError: Unexpected token <" when refreshing page in Vuejs-templates PWA

Lightrun Team
Lightrun Team
22-Jan-2023

Explanation of the problem

The issue being encountered is that upon performing a normal refresh of the webpage, the following error messages are displayed in the browser console:

manifest.48cbf0211cc2b417df60.js:1    Uncaught SyntaxError: Unexpected token <
vendor.e73f0cf5e42d1a1bdeee.js:1    Uncaught SyntaxError: Unexpected token <
app.d644989e00d1de883ada.js:1    Uncaught SyntaxError: Unexpected token <

Upon further investigation, it was discovered that when observing the Network tab in the browser developer tools, it appears that the entire HTML document (index.html) is being returned instead of the expected JavaScript files. An image of this can be seen in the following link: https://imgur.com/a/6AR5P

It is suspected that this issue may be caused by the source URLs for the JavaScript files returning a 404 error. However, it is important to note that this issue does not occur when performing a hard refresh (Ctrl + F5) of the webpage. Any suggestions or solutions to this problem would be greatly appreciated.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for “Uncaught SyntaxError: Unexpected token <” when refreshing page in Vuejs-templates PWA

The issue at hand is that upon performing a normal refresh of the webpage, JavaScript files are not loaded correctly and result in unexpected token errors. This is likely caused by the source URLs for the JavaScript files returning a 404 error. One possible reason for this is that the app is attempting to load JavaScript files from a previous version of the app which no longer exist. This can happen when there is a change in the file structure, naming conventions or if there’s a new version of the app is deployed.

One proposed solution is to add a <base href=”/” /> element into the <head> of the index.html file. The <base> tag is used to specify the base URL for all relative URLs in the page. This can help in resolving the 404 errors that are causing the unexpected token errors. It’s important to note that this solution may not work in all cases. It depends on the routing and file structure of the application.

Another approach to fix this issue is to use a service worker. Service workers can cache the JavaScript files and serve them even if the network is unavailable or slow. This approach is more robust than the <base> tag solution and it ensures that the app will work offline or in low-network conditions. However, this approach may require some additional setup and configuration. Also, it’s important to test the app in different network conditions and browsers to ensure that the caching mechanism works as expected.

Other popular problems with PWA

Problem: Caching and Offline Mode

One of the main challenges of PWAs is ensuring that the app works offline or in low-network conditions. While service workers can be used to cache assets and serve them offline, it can be difficult to determine the best strategy for caching and updating those assets.

Solution:

One popular solution is to use a library such as Workbox to handle caching and offline functionality. Workbox provides a set of libraries and Node modules that make it easy to configure and implement caching strategies for different types of assets.

Example of how to use workbox to cache the assets with a stale-while-revalidate strategy:

workbox.routing.registerRoute(
  /\.(?:js|css|html)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);

Problem: Add to home screen prompt

Another common challenge for PWAs is getting users to add the app to their home screen. The Add to Home Screen (A2HS) prompt is a browser feature that allows users to add a PWA to their home screen, but it only appears under certain conditions. The prompt may not appear if the user has not interacted with the app enough, or if the app is not served over HTTPS.

Solution:

One solution is to use a library such as the A2HS web API to programmatically prompt the user to add the app to their home screen. This can be done by listening to the beforeinstallprompt event and then using the prompt() method to display the A2HS prompt.

Example of how to prompt the user to add the app to their home screen:

let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPrompt = e;
    // Show the prompt
    deferredPrompt.prompt();
    // Wait for the user to respond to the prompt
    deferredPrompt.userChoice
    .then((choiceResult) => {
        if (choiceResult.outcome === 'accepted') {
            console.log('User accepted the A2HS prompt');
        } else {
            console.log('User dismissed the A2HS prompt');
        }
        deferredPrompt = null;
    });
});

Problem: Navigation and routing

One of the key features of PWAs is the ability to navigate between pages within the app without triggering a full page reload. However, implementing navigation and routing can be challenging, especially if the app uses client-side rendering or if the routing needs to work offline.

Solution:

One popular solution is to use a JavaScript library such as React Router or Angular Router to handle client-side routing. These libraries provide a set of components and APIs for declaratively defining the app’s routes, handling navigation events, and updating the URL and the UI.

Example of how to use React Router to define the routes and handle navigation:

import { BrowserRouter, Route, Link } from 'react-router-dom';

function App() {
    return (
        <BrowserRouter>
            <div>
                <nav>
                    <Link to="/">Home</Link>
                    <Link to="/about">About</Link>
                    <Link to="/contact">Contact</Link>
                </nav>
                <Route path="/" exact component={Home} />
                <Route path="/about" component={About} />
                <Route path="/contact" component={Contact} />
            </div>
        </BrowserRouter>
    );
}

function Home() {
    return <h2>Home</h2>;
}

function About() {
    return <h2>About</h2>;
}

function Contact() {
    return <h2>Contact</h2>;
}

In this example, the `BrowserRouter` component is used to define the root of the app‘s routing. The `Link` component is used to create navigation links, and the `Route` component is used to define the different routes and the components that should be rendered for each route. When the user clicks on a link or types a URL, React Router will update the app’s state, and the appropriate component will be rendered. The `exact` prop ensures that the home route only matches the exact path. It‘s important to note that this is just one example and there are many other libraries and approaches to handle navigation and routing in PWAs, but the key is to make sure that the navigation is fast, smooth, and works offline.

A brief introduction to PWA

Progressive Web Applications (PWAs) are web-based applications that aim to provide a native-like experience for users by combining the capabilities of web and mobile apps. PWAs are built using web technologies such as HTML, CSS, and JavaScript, and are designed to work offline, be fast, and be installable on the user’s device.

PWAs use a set of web standards and technologies to achieve a native-like experience. For example, they use service workers, a type of web worker that runs in the background, to cache assets and provide offline functionality. They also use web app manifests, a JSON file that contains metadata about the app such as its name, icons, and start URL, to make the app installable on the user’s device. Additionally, they use web APIs such as the A2HS web API and the Push API to provide features such as push notifications and offline support. PWAs are designed to work on all devices, regardless of whether it’s a desktop or mobile device and regardless of the browser. This allows PWAs to reach a wide range of users and can be a good alternative for native apps development.

Most popular use cases for PWA

  1. Building high-performance and engaging user interfaces: PWAs can be used to build web apps with high-performance and engaging user interfaces that are similar to those of native apps. This can be achieved by using web technologies such as React, Angular, or Vue.js, which allow for fast and efficient client-side rendering. PWAs can also leverage web animations and web APIs such as the Web Animations API and the Intersection Observer API to provide a smooth and responsive user experience.
  2. Creating offline-capable and low-latency apps: PWAs can be used to create web apps that work offline or in low-network conditions. This can be achieved by using service workers to cache assets and provide offline functionality. Service workers can also be used to intercept network requests and handle them in the background, which can help reduce the latency of the app.
  3. Building cross-platform apps: PWAs can be used to build web apps that can run on multiple platforms, including desktop, mobile, and tablet devices. This can be achieved by using web technologies such as HTML, CSS, and JavaScript, which are supported by all modern browsers. Additionally, PWAs can be wrapped in native containers, such as Apache Cordova, to provide access to native device features.

Example of how to use service worker to cache the files and serve them in offline mode:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js')
    .then(function(registration) {
        console.log('Service worker registration succeeded:', registration);
    })
    .catch(function(error) {
        console.log('Service worker registration failed:', error);
    });
} else {
    console.log('Service workers are not supported.');
}

This code will register the service worker file ‘sw.js’ and it will take control of the pages as soon as it’s installed and active.

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.