Skip to content

Commit

Permalink
feat: add loadScriptOnce, loadStylesOnce helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob-8 committed Apr 14, 2024
1 parent 8d344a9 commit 3d28dc2
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 4 deletions.
45 changes: 45 additions & 0 deletions src/lib/functions/loadOnce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const loadScript = (url: string) =>
new Promise<Event>((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.async = true;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});

export const loadScriptOnce = (() => {
const loaded = [];
return async function (url) {
if (!loaded.includes(url)) {
await loadScript(url);
loaded.push(url);
return true;
} else {
return true;
}
};
})();

const loadStyles = (url: string) =>
new Promise<Event>((resolve, reject) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
});

export const loadStylesOnce = (() => {
let loaded = [];
return async function (url) {
if (!loaded.includes(url)) {
await loadStyles(url);
loaded = [url];
return true;
} else {
return true;
}
};
})();
1 change: 1 addition & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export { default as Store } from './functions/Store.svelte';
export { default as ReactiveSet } from './functions/ReactiveSet.svelte';
export { default as IntersectionObserver } from './functions/IntersectionObserver.svelte';
export { default as IntersectionObserverShared } from './functions/IntersectionObserverShared.svelte';
export { loadScriptOnce, loadStylesOnce } from './functions/loadOnce.js';

export { default as QrCode } from './media/QrCode.svelte';

Expand Down
8 changes: 4 additions & 4 deletions src/lib/stores/query-param-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ function parse(value: string) {
}
}

export function createQueryParamStore<T>(opts: QueryParamStoreOptions<T>) {
const { key, log, persist, startWith, cleanFalseValues } = opts;
const replaceState = typeof opts.replaceState === 'undefined' ? true : opts.replaceState;
const storageKey = `${opts.storagePrefix || ''}${key}`
export function createQueryParamStore<T>(options: QueryParamStoreOptions<T>) {
const { key, log, persist, startWith, cleanFalseValues } = options;
const replaceState = typeof options.replaceState === 'undefined' ? true : options.replaceState;
const storageKey = `${options.storagePrefix || ''}${key}`

let storage: Storage = undefined
if (typeof window !== 'undefined') {
Expand Down

0 comments on commit 3d28dc2

Please sign in to comment.