Use different CSS file depending on URL path

794 views Asked by At

I have the following files:App.vue, changcolor.vue, config.json, main.js, index.html, xyz.css, abc.css.

Depending on the URL, i want to apply the right CSS file, so for example if URL is "xyz.local.com" then we'll use xyz.css and if "abc.local.com" then we'll use abc.local.com . And this also should be white labeling code.

2

There are 2 answers

1
ma_jafari On

How about making a new link tag and give the appropriate attributes depending on what the URL is. So it'll be like:

mounted() {
    let link = document.createElement('link');  
    link.rel = 'stylesheet';  
    link.type = 'text/css'; 
    let hostname = window.location.hostname
    hostname = name.split(".")[0]
    if(hostname == "abc"){
        link.href = "abc.css"
    } else {
        link.href = "xyz.css"
    }
    document.getElementsByTagName('HEAD')[0].appendChild(link);
}
0
Abu Sayed On

By checking current window location we can solve this problem. We just need to check the path name and load the css file.

//First get the pathname from current window location
const path = window.location.pathname;

//Now we can check whether our current location meet the path we wanted to check
if (path.includes('page-name-1')) {
  loadCSSFile('css/page1.css');
} else if (path.includes('page-name-2')) {
  loadCSSFile('css/page2.css');
} else {
  loadCSSFile('css/page3.css');
}

//This function will create a link tag in our site and load the file. This function take href as a parameter
function loadCSSFile(href) {
  const linkElement = document.createElement('link');
  linkElement.rel = 'stylesheet';
  linkElement.href = href;
  document.head.appendChild(linkElement);
}