dennwc / dom

DOM library for Go and WASM

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Require(path string) file typing is weak (has work-around)

smoyer64 opened this issue · comments

Problem

The Require(path string) method uses

dom/require.go

Line 37 in 7f87333

if strings.HasSuffix(path, ".css") {
to determine whether a file is CSS simply based on its suffix and defaults all other files loaded to JS. This presents a problem for certain types of CSS files such as any of the fonts provided by fonts.googleapis.com as the URL returns a valid CSS document and properly sets its mime-type to text/css but Require(path string) adds it to the document as a script file.

For instance, the following code:

dom.Require("https://fonts.googleapis.com/icon?family=Material+Icons")

results in the this element in <head>:

<script async="" src="https://fonts.googleapis.com/icon?family=Material+Icons"></script>

A better solution would be to use the Content-Type header returned by the server to decide whether the provided path is a CSS file or a JS file. An added benefit is that the process can fail before it tries to load the added file to the page if the Content-Type doesn't match a supported type.

Workaround

I've temporarily solved this problem by adding a URL fragment to the end of the url as follows:

dom.Require("https://fonts.googleapis.com/icon?family=Material+Icons#.css")

This portion of the URL is not sent to the server but does match the prefix that Require(path string) expects and results in the expected HTML element:

<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons#.css">

Perfect ... I don't know why I didn't think of simplifying the issue instead of using the mime-type. I always know whether I'm loading a stylesheet or javascript!