I've got 3 pages: index.hml, admin.html and host.html. I've got javascript on the pages inside script tags. I want to move all the javascript to one file, and have that available on each page.
I've tried linking to the JS file from my html pages like:
<script src="static/app.js" type= "text/javascript"></script>
but I keep getting the error:
Uncaught SyntaxError: Unexpected token <
I've tried playing around with this src path, including moving the app.js file to the same level as the html file, and changing src to "app.js" but that still gives the same error message.
This makes me think it's due to how the server is rendering the files (using a ServeMux).
my code is:
func requestHandler(tpl *template.Template) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tpl.Execute(w, r)
})
}
func main() {
flag.Parse()
user := template.Must(template.ParseFiles("index.html"))
admin := template.Must(template.ParseFiles("admin.html"))
host := template.Must(template.ParseFiles("host.html"))
router := http.NewServeMux()
router.Handle("/", requestHandler(user))
router.Handle("/admin", requestHandler(admin))
router.Handle("/host", requestHandler(host))
log.Fatal(http.ListenAndServe(":8081", router))
}
I've searched SO and tried many things including:
http.Handle("/js", http.FileServer(http.Dir("static/")))
with a javascript file inside static/app.js however this just renders my index page with no JS loaded. I can't seem to get a JS file to load into the page.
I've also tried reading the JS file, changing the content type and writing the JS file to the writer like so:
data, err := ioutil.ReadFile("app.js")
if err != nil {
fmt.Println("error: ", err)
return
}
w.Header().Add("Content Type", "application/javascript")
w.Write(data)
however this just renders all the text to the page with the JS not running, and the text not being renderd as HTML. On the page I see:
alert("loaded");<!DOCTYPE html>
<html>
<head>
<title>Example</title>
index.html header is:
<!DOCTYPE html>
<html>
<head>
<title>Chat Example</title>
</script>
<script src="static/app.js" type= "text/javascript"></script>
I feel there's got to be an easier way to load the JS. This is attempt 2 with more explanation, code and examples of what I tried.