|
7 | 7 | "text/template" |
8 | 8 |
|
9 | 9 | "github.com/xyproto/algernon/utils" |
| 10 | + "github.com/xyproto/huldra" |
10 | 11 | ) |
11 | 12 |
|
12 | 13 | const autoloadTemplate = ` |
@@ -96,16 +97,24 @@ func InsertScriptTag(htmldata, js []byte) []byte { |
96 | 97 | return js |
97 | 98 | } |
98 | 99 |
|
| 100 | + // TODO: Write a better HTML manipulator. Create an external package. |
| 101 | + |
99 | 102 | // Place the script at the end of the body, if there is a body |
100 | 103 | switch { |
101 | 104 | case bytes.Contains(htmldata, []byte("</body>")): |
102 | 105 | return bytes.Replace(htmldata, []byte("</body>"), append(js, []byte("</body>")...), 1) |
103 | 106 | case bytes.Contains(htmldata, []byte("<head>")): |
104 | 107 | // If not, place the script in the <head>, if there is a head |
105 | 108 | return bytes.Replace(htmldata, []byte("<head>"), append([]byte("<head>"), js...), 1) |
106 | | - case bytes.Contains(htmldata, []byte("<html>")): |
| 109 | + case huldra.IsHTML(htmldata): |
| 110 | + const maxPosition = 200 |
| 111 | + htmlTagBytes, err := huldra.GetHTMLTag(htmldata, maxPosition) // try to retrieve the entire <html[...]> tag |
| 112 | + if err != nil { |
| 113 | + htmlTagBytes = []byte("<html>") |
| 114 | + } |
| 115 | + htmlAndHeadTagBytes := append(htmlTagBytes, []byte("<head>")...) |
107 | 116 | // If not, place the script in the <html> as a new <head> |
108 | | - return bytes.Replace(htmldata, []byte("<html>"), append(append([]byte("<html><head>"), js...), []byte("</head>")...), 1) |
| 117 | + return bytes.Replace(htmldata, htmlTagBytes, append(append(htmlAndHeadTagBytes, js...), []byte("</head>")...), 1) |
109 | 118 | } |
110 | 119 |
|
111 | 120 | // In the unlikely event that no place to insert the JavaScript was found, just add the script tag to the end |
|
0 commit comments