I'm trying to add a CSS theme file globally inside the root component App.vue in a Vue3 project. I have to process it as a component props (I can't change this behavior since the css file can change dynamically and I need to handle this change every time it is mounted again), so the link will be available once the whole app is mounted.
I've been trying to achieve this inside App.vue appending to the header a <link> tag but I'm getting the MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled. error even if I specified the text/css type:
export default defineComponent({
name: "Application",
props: {
themeUrl: {
type: String,
required: false,
},
},
data() {
return {};
},
created() {
if (this.themeUrl) {
console.log(this.themeUrl);
let file = document.createElement("link");
file.rel = "stylesheet";
file.type = "text/css";
file.href = this.themeUrl;
document.head.appendChild(file);
}
},
});
</script>
Is there a way to achieve this? I think I can get this theme url even before the app mounting phase but I don't know if and how to tell Vue to use it globally anyway.
If you have a direct link to the css file then this should be sufficient, make sure to remove the tag when unmounted if you need to swap the theme.
It looks that your file.type = "text/css"; is the cause of the issue.
mounted () {
const file = document.createElement('link')
file.rel = 'stylesheet'
file.href = 'https://gist.githubusercontent.com/eirikbakke/1059266/raw/d81dba46c76169c2b253de0baed790677883c221/gistfile1.css'
document.head.appendChild(file)
}
You could also fetch the file content and load it into an existing tag:
With this tag in the head :
<style id="customStyle"></style>
And a similar behavior in your component :
export default defineComponent({
name: "Application",
props: {
themeUrl: {
type: String,
required: false,
},
},
data() {
return {};
},
mounted() {
if (this.themeUrl) {
console.log(this.themeUrl);
fetch(this.themeUrl)
.then(response => {
response.text().then(content => {
document.getElementById('customStyle').innerHTML = content
})
})
}
},
});
</script>