Skip to content

avoid adding styles multiple times #55

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

Merged
merged 3 commits into from
Mar 26, 2018
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
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/dist
/test/cases
/test/js
/test/manual
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ module.exports = {
}
```

### Features

#### Using preloaded or inlined CSS

The runtime code detects already added CSS via `<link>` or `<style>` tag.
This can be useful when injecting CSS on server-side for Server-Side-Rendering.
The `href` of the `<link>` tag has to match the URL that will be used for loading the CSS chunk.
The `data-href` attribute can be used for `<link>` and `<style>` too.
When inlining CSS `data-href` must be used.

<h2 align="center">Maintainers</h2>

<table>
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --collectCoverageFrom='src/**/*.js' --coverage",
"test:manual": "webpack-dev-server test/manual/src/index.js --open --config test/manual/webpack.config.js",
"travis:lint": "npm run lint && npm run security",
"travis:test": "npm run test -- --runInBand",
"travis:coverage": "npm run test:coverage -- --runInBand"
Expand All @@ -44,7 +45,9 @@
"pre-commit": "^1.2.2",
"standard-version": "^4.3.0",
"webpack": "^4.1.0",
"webpack-defaults": "^1.6.0"
"webpack-cli": "^2.0.13",
"webpack-defaults": "^1.6.0",
"webpack-dev-server": "^3.1.1"
},
"files": [
"dist"
Expand Down
34 changes: 32 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,43 @@ class MiniCssExtractPlugin {
Template.indent([
'promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {',
Template.indent([

`var href = ${linkHrefPath};`,
`var fullhref = ${mainTemplate.requireFn}.p + href;`,
'var existingLinkTags = document.getElementsByTagName("link");',
'for(var i = 0; i < existingLinkTags.length; i++) {',
Template.indent([
'var tag = existingLinkTags[i];',
'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");',
'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return resolve();',
]),
'}',
'var existingStyleTags = document.getElementsByTagName("style");',
'for(var i = 0; i < existingStyleTags.length; i++) {',
Template.indent([
'var tag = existingStyleTags[i];',
'var dataHref = tag.getAttribute("data-href");',
'if(dataHref === href || dataHref === fullhref) return resolve();',
]),
'}',
'var linkTag = document.createElement("link");',
'linkTag.rel = "stylesheet";',
'linkTag.type = "text/css";',
'linkTag.onload = resolve;',
'linkTag.onerror = reject;',
`linkTag.href = ${mainTemplate.requireFn}.p + ${linkHrefPath};`,
'linkTag.onerror = function(event) {',
Template.indent([
'var request = event && event.target && event.target.src || fullhref;',
'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + request + ")");',
'err.request = request;',
'reject(err);',
]),
'};',
'linkTag.href = fullhref;',
'var head = document.getElementsByTagName("head")[0];',
'head.appendChild(linkTag);',
]),
'}).then(function() {',
Template.indent([
'installedCssChunks[chunkId] = 0;',
]),
'}));',
Expand Down
Empty file added test/manual/README.md
Empty file.
48 changes: 48 additions & 0 deletions test/manual/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>mini-css-extract-plugin testcase</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="/dist/preloaded1.css" />
<style>
.test {
background: lightcoral;
}
.errors {
font-weight: bold;
color: darkred;
}
.preloaded-css1 {
background: lightgreen;
}
</style>
<style data-href="preloaded2.css">
.preloaded-css2 {
background: lightgreen;
}
</style>
<link rel="stylesheet" type="text/css" href="/dist/main.css" />
</head>
<body>
<div class="test initial-css">
Initial CSS: Must be green
</div>
<div class="test lazy-css">
<p>Lazy CSS: Must be red, but turn green when <button class="lazy-button">pressing this button</button>.</p>
<p>But turn orange, when <button class="lazy-button2">pressing this button</button>. Additional clicks have no effect.</p>
<p>Refresh and press buttons in reverse order: This should turn green instead.</p>
</div>
<div class="test preloaded-css1">
<p>Preloaded CSS: Must be green.</p>
<p><button class="preloaded-button1">Pressing this button</button> displays an alert but has no styling effect.</p>
</div>
<div class="test preloaded-css2">
<p>Preloaded inlined CSS: Must be green.</p>
<p><button class="preloaded-button2">Pressing this button</button> displays an alert but has no styling effect.</p>
</div>
<div class="errors"></div>
<script async defer src="/dist/main.js"></script>
</body>
</html>
22 changes: 22 additions & 0 deletions test/manual/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import './initial.css';

const handleError = (err) => {
document.querySelector(".errors").textContent += `\n${err.toString()}`;
console.error(err);
}

const makeButton = (className, fn) => {
const button = document.querySelector(className);
button.addEventListener("click", () => {
button.disabled = true;
fn().then(() => {
button.disabled = false;
}).catch(handleError);
});
}

makeButton(".lazy-button", () => import('./lazy.js'));
makeButton(".lazy-button2", () => import('./lazy2.css'));

makeButton(".preloaded-button1", () => import(/* webpackChunkName: "preloaded1" */ './preloaded1'));
makeButton(".preloaded-button2", () => import(/* webpackChunkName: "preloaded2" */ './preloaded2'));
3 changes: 3 additions & 0 deletions test/manual/src/initial.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.initial-css {
background: lightgreen;
}
3 changes: 3 additions & 0 deletions test/manual/src/lazy.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.lazy-css {
background: lightgreen;
}
1 change: 1 addition & 0 deletions test/manual/src/lazy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './lazy.css';
3 changes: 3 additions & 0 deletions test/manual/src/lazy2.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.lazy-css {
background: peru;
}
3 changes: 3 additions & 0 deletions test/manual/src/preloaded1.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.preloaded-css1 {
background: red;
}
3 changes: 3 additions & 0 deletions test/manual/src/preloaded1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import './preloaded1.css';

alert('Ok');
3 changes: 3 additions & 0 deletions test/manual/src/preloaded2.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.preloaded-css2 {
background: red;
}
3 changes: 3 additions & 0 deletions test/manual/src/preloaded2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import './preloaded2.css';

alert('Ok');
27 changes: 27 additions & 0 deletions test/manual/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const Self = require('../../');

module.exports = {
mode: 'development',
output: {
publicPath: '/dist/',
},
module: {
rules: [
{
test: /\.css$/,
use: [
Self.loader,
'css-loader',
],
},
],
},
plugins: [
new Self({
filename: '[name].css',
}),
],
devServer: {
contentBase: __dirname,
},
};
Loading