Skip to content

Instantly share code, notes, and snippets.

@joecritch
Last active July 13, 2017 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joecritch/760f9de259242dacb70bb93a78ffb8c3 to your computer and use it in GitHub Desktop.
Save joecritch/760f9de259242dacb70bb93a78ffb8c3 to your computer and use it in GitHub Desktop.
StylesheetLoader
<?php
$ssHrefs = array();
if (isset($stylesheets)):
foreach ($stylesheets as $ss):
$href = '/dist/styles/' . $ss;
$ssHrefs[] = $href;
// "Server-side render" the link elements
echo '<link rel="stylesheet" href="' . $href . '" />';
endforeach;
endif;
$stylesheetsJSON = sizeof($ssHrefs) > 0 ? json_encode($ssHrefs) : '';
?>
<div id="barba-wrapper" data-behavior="StylesheetLoader">
<div
class="barba-container"
<?php if ($stylesheetsJSON): // Allows Barba to read the latest required stylesheets ?>
data-StylesheetLoader-hrefs='<?php echo $stylesheetsJSON; ?>'
<?php endif; ?>
>
</div>
</div>
import Barba from 'barba.js';
import createBehavior from '../helpers/createBehavior';
const StylesheetLoader = createBehavior('StylesheetLoader', {
getStylesheetHrefs(container) {
const hrefs = container.getAttribute('data-StylesheetLoader-hrefs');
if (hrefs) {
return JSON.parse(hrefs);
}
return [];
}
}, {
init() {
this.stylesheetHrefs = this.getStylesheetHrefs(document.querySelector('.barba-container'));
Barba.Dispatcher.on('newPageReady', (currentStatus, oldStatus, container) => {
const nextStylesheetHrefs = this.getStylesheetHrefs(container);
const enteringStylesheetHrefs = nextStylesheetHrefs.slice(0);
this.stylesheetHrefs.forEach(href => {
if (nextStylesheetHrefs.includes(href)) {
// Not a new stylesheet
const enteringIndex = enteringStylesheetHrefs.indexOf(href);
enteringStylesheetHrefs.splice(enteringIndex, 1);
} else {
// Delete the <link>
document.head.querySelector('link[href="' + href + '"]').remove();
}
});
enteringStylesheetHrefs.forEach(href => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
document.head.appendChild(link);
});
this.stylesheetHrefs = nextStylesheetHrefs;
});
}
});
export default StylesheetLoader;
@joecritch
Copy link
Author

This behavior injects stylesheet <link /> elements, based on the dependencies for a particular page. This is useful for a PJAX pattern where the navigated-to pages have their own stylesheets.

You can do a similar thing by just including <link> elements directly in the body. However, because of the way Chrome handles links in the body, you'll get a flash of unstyled content on every page change (even if the stylesheet is cached). It's a pretty jarring experience. The advantage of doing it via JavaScript is that, if the stylesheet dependency exists on both the old and new page, it will keep the reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment