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

feat(core): CHECKOUT-4909 Pass in attributes to stylesheet #11

Merged
merged 1 commit into from
May 25, 2020
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
12 changes: 12 additions & 0 deletions src/stylesheet-loader.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ describe('StylesheetLoader', () => {
expect(document.head.appendChild)
.toHaveBeenCalledTimes(1);
});

it('attaches stylesheet tag to document with data attributes', async () => {
await loader.loadStylesheet(
'https://foo.bar/hello-world.css',
{prepend: true, attributes: {'data-attribute1': '1', 'data-attribute2': '2'}});

expect(stylesheet.attributes.getNamedItem('data-attribute1')!.value)
.toEqual('1');

expect(stylesheet.attributes.getNamedItem('data-attribute2')!.value)
.toEqual('2');
});
});

describe('when stylesheet fails to load', () => {
Expand Down
12 changes: 11 additions & 1 deletion src/stylesheet-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ import BrowserSupport from './browser-support';

export interface LoadStylesheetOptions {
prepend: boolean;
attributes?: StylesheetAttributes;
}

export interface PreloadStylesheetOptions {
prefetch: boolean;
}

export interface StylesheetAttributes {
[key: string]: string;
}

export default class StylesheetLoader {
private _stylesheets: { [key: string]: Promise<void> } = {};
private _preloadedStylesheets: { [key: string]: Promise<void> } = {};
Expand All @@ -26,7 +31,12 @@ export default class StylesheetLoader {
if (!this._stylesheets[src]) {
this._stylesheets[src] = new Promise((resolve, reject) => {
const stylesheet = document.createElement('link');
const { prepend = false } = options || {};
const { prepend = false, attributes = {} } = options || {};

Object.keys(attributes)
.forEach(key => {
stylesheet.setAttribute(key, attributes[key]);
});

stylesheet.onload = () => resolve();
stylesheet.onerror = event => {
Expand Down