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)
}
}
});
}
...