Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load script helper #15

Merged
merged 2 commits into from
May 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/App.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { PopStateData } from './Router/Router';
import type { Template } from '@chialab/dna';
import { listen } from '@chialab/dna';
import { requestAnimationFrame } from './helpers';
import { requestAnimationFrame } from './Helpers/Animations';
import { Micro } from './Micro';

/**
Expand Down
27 changes: 27 additions & 0 deletions src/Helpers/Animations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { window } from '@chialab/dna';

/**
* requestAnimationFrame wrapper for support in Node environments.
* @param callback The callback to invoke.
* @return The numeric handle of the request.
*/
export function requestAnimationFrame(callback: FrameRequestCallback): number {
if (typeof window.requestAnimationFrame === 'function') {
return window.requestAnimationFrame(callback);
}

const timeout = setTimeout(() => callback(Date.now()), 0);
return timeout as unknown as number;
}

/**
* cancelAnimationFrame wrapper for support in Node environments.
* @param handle The handle to cancel.
*/
export function cancelAnimationFrame(handle: number) {
if (typeof window.cancelAnimationFrame === 'function') {
return window.cancelAnimationFrame(handle);
}

return clearTimeout(handle);
}
15 changes: 15 additions & 0 deletions src/Helpers/Env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { window } from '@chialab/dna';

/**
* Check if the current environment is browser based.
*/
export function isBrowser() {
return typeof window._jsdom === 'undefined';
}

/**
* Check if the current environment is node based.
*/
export function isNode() {
return typeof window._jsdom !== 'undefined';
}
22 changes: 22 additions & 0 deletions src/Helpers/Network.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { window } from '@chialab/dna';

/**
* Fetch wrapper for support in Node environments.
* @param input The url to fetch or options.
* @param init Init options for the request.
* @return A promise that resolves a response.
*/
export async function fetch(input: RequestInfo, init?: RequestInit | undefined): Promise<Response> {
if (typeof window.fetch === 'function') {
return window.fetch(input, init);
}

try {
const { default: factory } = await import('node-fetch');
return factory(input, init);
} catch {
//
}

throw new Error('Missing fetch implementation');
}
33 changes: 33 additions & 0 deletions src/Helpers/Scripts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { DOM, window } from '@chialab/dna';

/**
* Cache scripts promises.
*/
const SCRIPTS: Map<string, Promise<void>> = new Map();

/**
* Load a script using a <script> element.
* @param url Url to load.
* @param reload Should reload the script.
* @return A promise that resolves on script load.
*/
export function loadScript(url: string | URL, reload = false) {
const href = typeof url === 'string' ? url : url.href;

let promise = SCRIPTS.get(href);
if (!promise || reload) {
const script = DOM.createElement('script');
script.src = href;

promise = new Promise<void>((resolve, reject) => {
script.addEventListener('load', () => resolve());
script.addEventListener('error', () => reject());
script.addEventListener('abort', () => reject());
window.document.head.appendChild(script);
});

SCRIPTS.set(href, promise);
}

return promise;
}
55 changes: 55 additions & 0 deletions src/Helpers/StyleSheets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { DOM, window } from '@chialab/dna';

/**
* Cache links promises.
*/
const LINKS: Map<string, [HTMLLinkElement, Promise<HTMLLinkElement>]> = new Map();

/**
* Load a stylesheet using a <link> element.
* @param url Url to load.
* @param reload Should reload the link.
* @return A promise that resolves on link load.
*/
export function loadStyleSheet(url: string | URL, reload = false): Promise<HTMLLinkElement> {
const href = typeof url === 'string' ? url : url.href;
const loader = LINKS.get(href);

let promise;
if (!loader || reload) {
const link = DOM.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = href;

promise = new Promise<HTMLLinkElement>((resolve, reject) => {
link.addEventListener('load', () => (link.parentNode ? resolve(link) : reject(link)));
link.addEventListener('error', () => reject(link));
link.addEventListener('abort', () => reject(link));
window.document.head.appendChild(link);
});

LINKS.set(href, [link, promise]);
} else {
promise = loader[1];
}

return promise;
}

/**
* Unload a stylesheet.
* @param url Url of the stylesheet to unload.
*/
export function unloadStyleSheet(url: string | URL) {
const href = typeof url === 'string' ? url : url.href;

const loader = LINKS.get(href);
if (!loader) {
return;
}

const link = loader[0];
window.document.head.removeChild(link);
LINKS.delete(href);
}
90 changes: 0 additions & 90 deletions src/helpers.ts

This file was deleted.

6 changes: 5 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,9 @@ export { History } from './Router/History';
export { Router } from './Router/Router';
export { Micro } from './Micro';
export { App } from './App';
export * from './helpers';
export * from './Helpers/Env';
export * from './Helpers/Network';
export * from './Helpers/Animations';
export * from './Helpers/Scripts';
export * from './Helpers/StyleSheets';
export { DocumentMetaMiddleware } from './Router/DocumentMetaMiddleware';