Skip to content

Commit 8fc0007

Browse files
committed
Cache options parsing
This way it can be called multiple times without incurring extra overhead or potentially resolving in a different way. Also catch any errors when parsing query options just as we do with the options in the markup and log errors with the latter as well.
1 parent a7940d3 commit 8fc0007

File tree

1 file changed

+28
-19
lines changed

1 file changed

+28
-19
lines changed

src/common/util.ts

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -66,33 +66,42 @@ export const resolveBase = (base?: string): string => {
6666
return normalize(url.pathname)
6767
}
6868

69+
let options: Options
70+
6971
/**
7072
* Get options embedded in the HTML or query params.
7173
*/
7274
export const getOptions = <T extends Options>(): T => {
73-
let options: T
74-
try {
75-
options = JSON.parse(document.getElementById("coder-options")!.getAttribute("data-settings")!)
76-
} catch (error) {
77-
options = {} as T
78-
}
75+
if (!options) {
76+
try {
77+
options = JSON.parse(document.getElementById("coder-options")!.getAttribute("data-settings")!)
78+
} catch (error) {
79+
console.error(error)
80+
options = {} as T
81+
}
7982

80-
// You can also pass options in stringified form to the options query
81-
// variable. Options provided here will override the ones in the options
82-
// element.
83-
const params = new URLSearchParams(location.search)
84-
const queryOpts = params.get("options")
85-
if (queryOpts) {
86-
options = {
87-
...options,
88-
...JSON.parse(queryOpts),
83+
// You can also pass options in stringified form to the options query
84+
// variable. Options provided here will override the ones in the options
85+
// element.
86+
const params = new URLSearchParams(location.search)
87+
const queryOpts = params.get("options")
88+
if (queryOpts) {
89+
try {
90+
options = {
91+
...options,
92+
...JSON.parse(queryOpts),
93+
}
94+
} catch (error) {
95+
// Don't fail if the query parameters are malformed.
96+
console.error(error)
97+
}
8998
}
90-
}
9199

92-
options.base = resolveBase(options.base)
93-
options.csStaticBase = resolveBase(options.csStaticBase)
100+
options.base = resolveBase(options.base)
101+
options.csStaticBase = resolveBase(options.csStaticBase)
102+
}
94103

95-
return options
104+
return options as T
96105
}
97106

98107
/**

0 commit comments

Comments
 (0)