- Saved searches
- Use saved searches to filter your results more quickly
- License
- filamentgroup/loadCSS
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- webdevetc
- . . . my software engineering blog (Typescript, Vue, Laravel, PHP, Javascript, React, Docker, etc).
- How to set up style loader and css loader with webpack, to include CSS style files when building your JS app
- Table of contents
- Including your CSS stylesheet in your Javascript file
- Install some webpack loaders to make use of your CSS stylesheet import
- Update webpack.config.js and add the CSS loaders
- Use webpack to build your assets and export to separate CSS stylesheet files
- Install mini-css-extract-plugin to extract the CSS to its own file
- Update webpack.config.js to use MiniCssExtractPlugin
- How to export different CSS files from webpack
- How to setup Sass/Scss stylesheets with webpack
- Install Sass and the webpack Sass loader packages
- Set up webpack config to use the sass loaders
- Part of my webpack series
- About me
- Popular Posts
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
filamentgroup / loadCSS Public archive
License
filamentgroup/loadCSS
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
⚠️ This project is archived and the repository is no longer maintained.
A pattern for loading CSS asynchronously [c]2020 @scottjehl, @zachleat Filament Group, Inc. Licensed MIT
Why an ansychronous CSS loader?
Referencing CSS stylesheets with link[rel=stylesheet] or @import causes browsers to delay page rendering while a stylesheet loads. When loading stylesheets that are not critical to the initial rendering of a page, this blocking behavior is undesirable. The pattern below allows us to fetch and apply CSS asynchronously. If necessary, this repo also offers a separate (and optional) JavaScript function for loading stylesheets dynamically.
As a primary pattern, we recommend loading asynchronous CSS like this from HTML:
That is probably all you need! But if you want to load a CSS file from a JavaScript function, read on.
Dynamic CSS loading with the loadCSS function
The loadCSS.js file exposes a global loadCSS function that you can call to load CSS files programmatically, if needed. This is handy for cases where you need to dynamically load CSS from script.
loadCSS( "path/to/mystylesheet.css" );
The code above will insert a new CSS stylesheet link after the last stylesheet or script that it finds in the page, and the function will return a reference to that link element, should you want to reference it later in your script. Multiple calls to loadCSS will reference CSS files in the order they are called, but keep in mind that they may finish loading in a different order than they were called.
The loadCSS function has 3 optional arguments.
- before : By default, loadCSS attempts to inject the stylesheet link after all CSS and JS in the page. However, if you desire a more specific location in your document, such as before a particular stylesheet link, you can use the before argument to specify a particular element to use as an insertion point. Your stylesheet will be inserted before the element you specify. For example, here’s how that can be done by simply applying an id attribute to your script .
head> . script id pl-s">loadcss"> // load a CSS file just before the script element containing this code loadCSS( "path/to/mystylesheet.css", document.getElementById("loadcss") ); script> . head>
- media : You can optionally pass a string to the media argument to set the media=»» of the stylesheet — the default value is all .
- attributes : You can also optionally pass an Object of attribute name/attribute value pairs to set on the stylesheet. This can be used to specify Subresource Integrity attributes:
loadCSS( "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css", null, null, "crossorigin": "anonymous", "integrity": "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" > );
Onload event support for link elements is spotty in some browsers, so if you need to add an onload callback, include onloadCSS function on your page and use the onloadCSS function:
var stylesheet = loadCSS( "path/to/mystylesheet.css" ); onloadCSS( stylesheet, function() console.log( "Stylesheet has loaded." ); >);
The loadCSS patterns attempt to load a css file asynchronously in any JavaScript-capable browser. However, some older browsers such as Internet Explorer 8 and older will block rendering while the stylesheet is loading. This merely means that the stylesheet will load as if you referenced it with an ordinary link element.
Changes in version 3.0 (no more preload polyfill)
As of version 3.0, we no longer support or include a polyfill for a rel=preload markup pattern. This is because we have since determined that the markup pattern described at the top of this readme is simpler and better for performance, while the former preload pattern could sometimes conflict with resource priorities in ways that aren’t helpful for loading CSS in a non-blocking way.
To update, you can change your preload markup to this HTML pattern and delete the JS from your build.
Since this change breaks the API from prior versions, we made it a major version bump. That way, if you are still needing to use the now-deprecated preload pattern, you can keep your code pointing at prior versions that are still on NPM, such as version 2.1.0 https://github.com/filamentgroup/loadCSS/releases/tag/v2.1.0
Contributions and bug fixes
Both are very much appreciated — especially bug fixes. As for contributions, the goals of this project are to keep things very simple and utilitarian, so if we don’t accept a feature addition, it’s not necessarily because it’s a bad idea. It just may not meet the goals of the project. Thanks!
webdevetc
. . . my software engineering blog
(Typescript, Vue, Laravel, PHP, Javascript, React, Docker, etc).
How to set up style loader and css loader with webpack, to include CSS style files when building your JS app
Table of contents
If you need to start by installing webpack and getting the basics (before setting up babel) installed then checkout my guide to setting up Webpack — then come back here to continue and install babel.
Including your CSS stylesheet in your Javascript file
I am going to assume at this point you have webpack set up, and have a JS file such as index.js .
Create a CSS file with some rules in.
Then in your index.js (or `app.js, etc) you have to import that CSS file in:
Install some webpack loaders to make use of your CSS stylesheet import
Run the following to install a couple of packages which will help include the stylesheets
yarn add -D style-loader css-loader
Update webpack.config.js and add the CSS loaders
If you do not have a webpack.config.js file then create it. Update it with the CSS rule below:
const path = require('path'); module.exports = entry: './src/app.js', output: filename: '[name].js', path: path.resolve(__dirname, 'dist') >, module: rules: [ test: /\.js$/, exclude: /node_modules/, use: loader: 'babel-loader', options: presets: ['@babel/preset-env'] > > >, // Relevant bit of config for style loader and css loader: test: /\.css$/, // the order of `use` is important! use: [ loader: 'style-loader' >, loader: 'css-loader' >], >, ] >, >;
Now when you build your assets with webpack, your compiled JS file will also include your CSS rules.
Use webpack to build your assets and export to separate CSS stylesheet files
The config so far has imported your CSS, and combined it in the JS that is built in /dist/index.js .
You will probably actually want to have a separate .css file, instead of combining it with your JS file.
Install mini-css-extract-plugin to extract the CSS to its own file
Run yarn add -D mini-css-extract-plugin .
Update webpack.config.js to use MiniCssExtractPlugin
Once you have the package installed, you must update your webpack.config.js file
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const path = require('path'); module.exports = plugins: [ new MiniCssExtractPlugin( filename: "[name].css", >), ], entry: 'index': './src/index.js', >, output: filename: '[name].js', path: path.resolve(__dirname, 'dist'), >, module: rules: [ test: /\.js$/, loader: 'source-map-loader'>, // Relevant config for MiniCssExtractPlugin: // (the order of `use` is important) test: /\.css$/i, use: [MiniCssExtractPlugin.loader, 'css-loader'], >, ], >, >;
How to export different CSS files from webpack
If you have several different CSS files and you wish to build them as different files (in /dist ), e.g. /dist/style.css , /dist/admin-panel.js then you can do the following:
//. entry: 'index': './src/index.js', // (your main JS) 'style': './src/public-css.css', // (first css file) 'admin-panel': './src/admin-panel-css.css', // (another css file) >, output: filename: '[name].js', path: path.resolve(__dirname, 'dist'), >, // .
How to setup Sass/Scss stylesheets with webpack
I love Sass! It makes developing CSS much easier and quicker. Here is a guide to setting up Sass in your webpack config so you can build from Sass files and export css files.
Install Sass and the webpack Sass loader packages
yarn add -D node-sass sass-loader
Set up webpack config to use the sass loaders
In the rules part of your webpack config, add a rule for .scss / .sass files.
test: /\.s[ac]ss$/i, use: [ MiniCssExtractPlugin.loader, "css-loader", "sass-loader", ] >
Part of my webpack series
About me
This is my site where I post some software engineering posts/content. Some articles are in depth, some are more like notes.
I mostly focusing on Laravel, Vue, PHP, JS, Typescript, Golang, Docker etc.