Reputation: 67
I am trying to add an external css file and i got to know a method to add using this answer Adding External Stylesheet using JavaScript
and using that i am trying to add the external file but getting the error here is the code which i am tried to run
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 class="heading">Hello</h2>
<script>
var element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", "main.css");
document.getElementsByTagName("head")[0].appendChild(element);
</script>
</body>
</html>`
async function handleRequest(request) {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
}
addEventListener('fetch', (event) => {
return event.respondWith(handleRequest(event.request))
})
and when i run this code in firefox then this error comes
The stylesheet https://staticpage.practice.workers.dev/main.css was not loaded because its MIME type, “text/html”, is not “text/css”.
Upvotes: 0
Views: 397
Reputation: 45171
The problem is that you're serving the same HTML from every path.
When you visit your site in your browser, first the browser requests the page, and it gets back HTML as it expected. But your HTML contains some JavaSript which constructs a tag like: <link rel="stylesheet" type="text/css" href="main.css">
When your browser sees this, it tries to load main.css
as a stylesheet. Since this is a relative path, it tries to load it from the same server that served the HTML. But that server is your worker, and your worker always returns your HTML in response to every request. So when the browser requests main.css
, it gets the HTML again. This isn't a valid stylesheet, so it complains with the error you saw.
You could try changing your worker's handleRequest()
method to be something like:
async function handleRequest(request) {
let url = new URL(request.url);
if (url.pathname === "/") {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
} else if (url.pathname === "/main.css") {
// TODO: return your stylesheet here.
} else {
return new Response("Not found", {status: 404});
}
}
Alternatively, if you meant to load the stylesheet from a different hostname, not from your worker, then you should change this line:
element.setAttribute("href", "main.css");
to contain a fully-qualified URL, like:
element.setAttribute("href", "https://example.com/main.css");
Upvotes: 1