Ways to correctly import various CSS files for individual routes in a Vuejs application

Currently, I am in the process of developing a project using Vue.js and Laravel. This project will have distinct layouts for the admin/user panel and landing page, requiring different CSS files to be loaded for each route.

At the moment, I am utilizing vanilla JavaScript to determine which CSS file should be loaded based on the route. However, I am curious if there is a more efficient or proper method to accomplish this task?

Here is my current approach:

In each route, there is an array specifying the CSS files that need to be loaded. If a particular CSS file is already loaded, the script will ignore it. If it is not loaded, a <link> element will be appended to load the CSS file. In cases where a CSS file is no longer required, it will be disabled. If a CSS file is included but disabled, it will be re-enabled.

router.beforeEach((to, from, next) => {

  // Load styles
  if (to.meta.styles) {
    to.meta.styles.forEach((item, i) => {
      let element = document.querySelector(`[rel="stylesheet"][href="${item}"][class="appStyles"]`);

      if (!element) {
        var link = document.createElement( "link" );
        link.href = item;
        link.type = "text/css";
        link.rel = "stylesheet";
        link.setAttribute("class", "appStyles");
        document.getElementsByTagName( "head" )[0].appendChild( link );
      }
    });
  }

  // Disable styles
  let existingStyleSheet = document.querySelectorAll(`[rel="stylesheet"][class="appStyles"]`);
  if (existingStyleSheet) {
    existingStyleSheet.forEach((item, i) => {
      if (to.meta.styles) {
        let needed = 0;
        to.meta.styles.forEach((stylesheet, i) => {
          if (item.href == stylesheet) {
            needed += 1;
          }
        });

        item.disabled = false
        if (needed == 0) {
          item.disabled = true
          item.parentNode.removeChild(item)
        }
      }
    });
  }

...

Answer №1

Consider an alternate approach by loading a single CSS file in the traditional manner (within header tags) and assigning a specific class to the body tag based on the layout or page being viewed. While this may result in some unwanted styling, it will simplify the code structure and make maintenance easier. Take a look at this example:

$h2-orange: #f60;
$h2-green: #0f0;

/* Shared styles for consistency */
.h2 {
    font-size: 40px;
    letter-spacing: 1.5px;
}

/* Theme 1 customization */
.orange-theme {
    .h2 {
        color: $h2-blue;
    }
    /* Additional styles specific to Theme 1 */
}

/* Theme 2 customization */
.green-theme {
    .h2 {
        color: $h2-green;
    }
    /* Additional styles specific to Theme 2 */
}

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

What could be causing my webpage content to be partially hidden by my CSS menu?

I am currently working on my website which features a CSS menu with my website logo, a text box, and a dropdown. Additionally, I have created a login form using a table like the one shown below. <p>&nbsp;</p><table width="40%" border="0 ...

Having trouble getting the toggle button JavaScript code to function properly in React JS?

I'm in need of some assistance with the comment section located below the JavaScript Code. I am trying to implement a toggle button / hamburger button, but it seems that addEventListener is not necessary for ReactJS. Can someone provide guidance on wh ...

Is it possible to iterate through div elements using .each while incorporating .append within an AJAX call?

After sending AJAX requests and receiving HTML with multiple div elements (.card), I am using .append to add new .card elements after each request, creating an infinite scroll effect. However, I am facing issues when trying to use .each to iterate over all ...

What is the best way to trigger dependent APIs when a button is clicked in a React Query application

On button click, I need to call 2 APIs where the second query depends on the result of the first query. I want to pass data from the first query to the second query and believe using "react-query" will reduce code and provide necessary states like "isFetch ...

What is the best way to have an image fill the remaining space within a 100vh container automatically?

I have a container with a height of 100vh. Inside it, there is an image and some text. The text's height may vary based on the screen size and content length. I want the text to occupy its required space while the image fills up the remaining availabl ...

PHP Unable to Locate the header.html File Within the Specified Directory

Currently, I am facing an issue while trying to use PHP to incorporate the same header, navigation, and footer elements on all my website pages. The problem arises when the .php file fails to recognize the header.html file for an include("/header.html") op ...

Issue with Laravel's hasManyThrough Relationship not functioning as expected

Imagine the scenario where three tables are present as described below: projects- id, name environments- id, project_id, environment_id deployments- id, commit_hash In this setup, project id and deployment id are stored in environments. Both envi ...

Having trouble reading the file using jQuery in Internet Explorer 8 and earlier versions due to its non-XML format (albeit resembling XML)

Currently, I am utilizing AJAX to load a KML file (which essentially functions as an XML file). The parsing works seamlessly in IE9, FF, and other browsers, but encounters issues in IE8. Although the data is retrieved, I face difficulties parsing it in jQu ...

Guide to dynamically updating a textarea in vue.js by incorporating data from several inputs

Is there a way to update a textarea based on multiple inputs using jQuery and vue.js? I have successfully implemented the jQuery part with line breaks, but when I try to display the value of the textarea elsewhere using vue.js, it doesn't seem to work ...

Personalize your material-ui popover

Seeking assistance in customizing the shape of a material-ui popover similar to the one depicted in the image. https://i.sstatic.net/l5uNL.png I have created a working demo of the popover using React and provided a link for editing purposes. Any help? =& ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Issues with Node JS app's handling of php mailer code

I've made a basic website using the Node JS framework and included a php mailer for handling the contact form. Unfortunately, I'm facing issues getting it to function properly. Could it be possible that there is an underlying problem with Node JS ...

How to create a clickable link using Vuetify's v-btn component

As a newcomer to vue and vuetify, I would greatly appreciate some explanation and examples. My goal is to create a button that directs users to an external site, like youtube.com. Below is the code I currently have, but unfortunately it's not function ...

confirmation message upon completing a form submission

<script> var remainingCredit = document.getElementById("cor_credit"); var remaining = document.getElementById("remain_credit"); function validateForm() { if (remaining.value < remainingCredit.value) { return conf ...

Update the variable values in the Onclick function

I am trying to modify the onClick function attached to a button. My goal is to change the function var from 'create' to 'update' when the page loads and also through other functions. I attempted the code below but it did not work as exp ...

Customize each Picker.Item element in React Native with unique styles

How can I style individual Picker.Items beyond just changing the text color? Additionally, what other props can be used for a Picker.Item? I am aware of "key", "value", "label", and "color". Are there any additional props available? I want to customize o ...

Embed a data entry point into an existing picture

Looking for assistance inserting a field within an image for users to enter their email. Can someone provide the HTML code for this? Appreciate your help! ...

You can use AJAX, JQuery, or JavaScript in PHP to upload a total of 7 files by utilizing 7 individual file input

My client has a unique request - they want to be able to upload a file in PHP without using the traditional <form> tag or a submit button. While I am familiar with file uploads in PHP, I am unsure of how to achieve this without utilizing the <for ...

Aggregate X and Y values based on a key in a scatter plot using dc.js

Here is a glimpse of my dataset: var items = [ {name: "X", duration: 1, quantity: 2}, {name: "X", duration: 2, quantity: 1}, {name: "Y", duration: 1, quantity: 4}, {name: "X", duration: 3, quantity: 1 ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...