Skip to content

Commit

Permalink
Avoid FOUS when using FastBoot
Browse files Browse the repository at this point in the history
Closes #2
  • Loading branch information
alexlafroscia committed Jan 28, 2018
1 parent 7b1bb49 commit 10ad743
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
19 changes: 19 additions & 0 deletions addon/instance-initializers/hydrate-fastboot-styles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { get } from '@ember/object';
import { hydrate } from 'emotion';

export const FASTBOOT_STYLE_CACHE_NAME = 'emotion-ids';

export function initialize(appInstance) {
const fastboot = appInstance.lookup('service:fastboot');

if (fastboot && !get(fastboot, 'isFastBoot')) {
const shoebox = get(fastboot, 'shoebox');
const emotionIds = shoebox.retrieve(FASTBOOT_STYLE_CACHE_NAME);

hydrate(emotionIds);
}
}

export default {
initialize
};
4 changes: 4 additions & 0 deletions app/instance-initializers/hydrate-fastboot-styles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export {
default,
initialize
} from 'ember-emotion/instance-initializers/hydrate-fastboot-styles';
33 changes: 33 additions & 0 deletions fastboot/instance-initializers/setup-style-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { scheduleOnce } from '@ember/runloop';
import { get } from '@ember/object';
import emotion from 'emotion';

import { FASTBOOT_STYLE_CACHE_NAME } from 'ember-emotion/instance-initializers/hydrate-fastboot-styles';

export function initialize(application) {
const document = application.lookup('service:-document');
const fastboot = application.lookup('service:fastboot');
const shoebox = get(fastboot, 'shoebox');

// Generate the styles that we need to inject into the page
scheduleOnce('afterRender', function() {
const style = document.createElement('style');
const css = emotion.sheet.sheet.reduce((acc, style) => acc + style, '');

style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}

// Put IDs into showboe for re-hydration
shoebox.put(FASTBOOT_STYLE_CACHE_NAME, Object.keys(emotion.inserted));

document.head.appendChild(style);
});
}

export default {
initialize
};

0 comments on commit 10ad743

Please sign in to comment.