I have a React app that's loaded into a parent document via some shim JavaScript that:
- creates an
<iframe>
element - creates a
<div>
- injects a
<style>
tag into the<head>
in order to style the inserted<div>
Roughly, this works using the below:
// example.jsx
// Require the css using css-loader
const styles = require('../styles/example.css');
// Find the parent document
const doc = window.parent.document;
// Inject our stylesheet for the widget into the parent document's
// HEAD as a style tag
const css = styles.toString();
const style = doc.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
doc.head.appendChild(style);
This uses css-loader
in our Webpack config in order to have the require().toString()
work for setting the cssText
dynamically.
While this works, I don't know if this ideal. And we'd prefer to write Sass and get the benefits of @import
to bring in other CSS (like resets), and get the benefits other tooling for Sass.
Is there a better way that we can achieve the same result of injecting <style>
text into this parent document without sacrificing our ability to use the tooling we prefer?