I need to extract the used CSS from a 19,000 line CSS file where 98.4% of it is unused (ouch). I know you can use Chrome Developer Tools to view the CSS Coverage, like so:
But it doesn't allow you to even jump to the green lines. Manually going through 19K lines just doesn't seem feasible.
Chrome Lighthouse doesn't seem to give you an option to see only the rules you need like Developer Tools used to, either.
I've tried Firefox's "CSS Usage" add-on (which a lot of sites recommend) but it requires FireBug, which itself isn't compatible in the current version of FireFox.
Can anyone think of a way to pull out just the CSS that's used somehow?
Hope this will help you
https://uncss-online.com/
just add html in left and css in right. Click ok btn then see magic
if there is any error in css then it will ask you to remove that error in that line number.
This is the easiest methode :)
After downloading the Coverage .json from Chrome (>= v73) [What's New In DevTools - Chrome 73].
You can extract the CSS with this node script:
$ node extractCSS.js ~/Desktop/Coverage-20190325T110812.json
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
https://d33wubrfki0l68.cloudfront.net/css/1bd6a34e1fcf409d29d1a960e6299893fca2e7b1/css/all.css
https://unpkg.com/bootstrap#4.1.3/dist/css/bootstrap.min.css
./final_css.css file saved
// extractCSS.js
const fs = require('fs');
let final_css_bytes = '';
let total_bytes = 0;
let used_bytes = 0;
const filename = process.argv[2];
const output = './final_css.css';
if (!filename) {
console.error('Missing filename to get coverage information from');
process.exit();
}
const file_coverage = fs.readFileSync(filename);
const css_coverage = JSON.parse(file_coverage);
for (const entry of css_coverage) {
if (!entry.url.endsWith('.css')) continue;
console.log(entry.url);
final_css_bytes += '# ' + entry.url + '\n\n';
total_bytes += entry.text.length;
for (const range of entry.ranges) {
used_bytes += range.end - range.start - 1;
final_css_bytes += entry.text.slice(range.start, range.end) + '\n';
}
final_css_bytes += '\n\n';
}
fs.writeFile(output, final_css_bytes, error => {
if (error) {
console.log('Error creating file:', error);
return;
}
console.log(output, 'file saved');
});
https://gist.github.com/gianpaj/a2f99e022e2c3f8abb9deecb47d572c4
Inspired by: https://blog.fullstacktraining.com/remove-unused-css-javascript-code-from-your-project/
I use PurifyCSS for some of my projects. Helps me to keep my CSS lightweight.
Dont' know about your project structure and workflow, but there are tons of tutorials out there:
https://webdesign.tutsplus.com/tutorials/remove-unnecessary-css-with-purifycss-and-grunt--cms-27726
https://survivejs.com/webpack/styling/eliminating-unused-css/
There are also some online solutions for getting rid of unused CSS, never tried though:
https://uncss-online.com/
Related
I wrote a Script in about 1yr before.
Today when I run it again, the command HtmlService.createHtmlOutput(HTMLToOutput) seems not longer work, with this error shown on my Chrome (which hasn't disallowed Javascript):
"The current browser does not support this feature. Please upgrade to a newer browser."
My code is standard code inside doGet(e). Even this simplified version won't work also:
function doGet(e) {
...
HTMLToOutput = "<html><h1>Install this App into your Google Drive!</h1><a href='" + getURLForAuthorization() + "'>click here to start</a></html>";
return HtmlService.createHtmlOutput(HTMLToOutput).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getURLForAuthorization() {
return AUTHORIZE_URL + '?response_type=code&client_id=' + CLIENT_ID + '&redirect_uri=' + REDIRECT_URL + '&scope=' + AUTH_SCOPE;
}
Do anyone know the reason?
I had the same issue. I was able to solve it by adding this
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
so, total line should look like this:
HtmlService.createHtmlOutput(HTMLToOutput).setSandboxMode(HtmlService.SandboxMode.IFRAME);
To debug my chromium-embedded application I am looking for a function to get the source code of the web page from withing the chrome developer tools. I basically want the HTML tree shown in the 'Elements' tab, the actual HTML DOM, as HTML text. Does this functionality exist? How can I use it?
As I use CEF I do only have the chrome dev tools available and not the full browser. I cannot use the right-click context menu because I want to see the current manipulated DOM and not the original source.
I want to use this functionality for debugging purpose so that I can diff two different HTML trees.
Select the top node and choose "Copy". You'll have to re-add the Doctype, though.
Alternatively, you could click on "edit as HTML" and copy it from there.
update: extension has been released! Named Dump Dom
chrome store
github source
I found a better way to dump the current dom tree to a html file ( to persist your changes to the dom tree in the element tab ),just paste the code below to the console, and a dom.html file would be downloaded.
filename = "dom";
var html = '',
node = document.firstChild
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML
break
case Node.TEXT_NODE:
html += node.nodeValue
break
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>'
break
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->'
break
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html +=
'<!DOCTYPE ' +
node.name +
(node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') +
(!node.publicId && node.systemId ? ' SYSTEM' : '') +
(node.systemId ? ' "' + node.systemId + '"' : '') +
'>\n'
break
}
node = node.nextSibling
}
var file = new Blob([html], {
type: 'text/html'
});
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
Inspired from this project: https://github.com/wingleung/save-page-state.
And I would develop an extention to make on-click-dump functional later.
You can try the following:
All you have to do is right click the element and copy the outerHTML.
Our corporate wiki is Mediawiki. I have no problem to put iframe into my site to refer for some article on wiki.
But my own site have a lot of widgets and own style. I don't want to include Mediawiki navigation/search/login widgets, logo image.
Is it possible and how to get Mediawiki page contents without widgets (only article body)?
Yes, it is. You'll probably want to use the action=render url parameter, for example: http://en.wikipedia.org/w/index.php?action=render&title=Main_Page. Note that the stylesheets from the wiki aren't included, so you'll need to copy the relevant rules to your site's css files. See also this.
Thank waldir for answer!
After asking question I perform own research and end with code:
window.onload = function() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState !== 4) {
console.log("Not ready, code: %o", httpRequest.readyState);
return;
}
if (httpRequest.status !== 200) {
console.log("Server error: %o", httpRequest.status);
return;
}
var json = JSON.parse(httpRequest.responseText);
console.log("json: %o", json);
var wiki = json.query.pages["1"].revisions[0]["*"];
console.log("wiki: %o", wiki);
var html = InstaView.convert(wiki);
console.log("html: %o", html);
document.getElementById('area').innerHTML = html;
};
var url = 'https://wiki.evil-company.com/api.php?action=query&prop=revisions&format=json&titles=Main_page&rvprop=timestamp|user|comment|content';
httpRequest.open('GET', url, true);
httpRequest.send(null);
}
Here I use https://github.com/cscott/instaview/blob/master/main.js project which is enhanced http://en.wikipedia.org/wiki/User:Pilaf to transform json output to HTML on browser side.
The reason for this code because our wiki is old or misconfigured and action=render is not available. But I trap into cross-domain scripting issue so I think that iframe with action=render is better solution.
See also How do you grab an article including the links in a usable format?
Another suggestion to use action=parse (http://en.wikipedia.org/w/api.php?action=parse&title=Linux) lead to warning:
You are looking at the HTML representation of the XML format.
HTML is good for debugging, but is unsuitable for application use.
Specify the format parameter to change the output format.
UPDATE
Perfect solution just append query action=render to any valid wiki URL like:
http://en.wikipedia.org/wiki/Linux?action=render
Im looking for the equivalent of "tail -f" that runs in a browser using html5 or javascript.
A solution would need a client side code written in HTML5/websockets/javascript and a back-end server side application. Im looking for one in c# but i'm willing to rewrite it from php or python.
This is the only thing that i've seen that comes close is
http://commavee.com/2007/04/13/ajax-logfile-tailer-viewer/
However, modern browsers have WebSockets which makes the problem much simpler.
http://www.websocket.org/echo.html
Ideally, I would like to have some of the capabilities of BareTail
http://www.baremetalsoft.com/baretail/
Such as Color Coding of lines, sorting and multi-file tabbing.
I have located a similar posting where someone is looking for windows based log file programs
https://stackoverflow.com/questions/113121/best-tail-log-file-visualization-freeware-tool
Anyone have any suggestions?
It is not exactly like tail but the live logs feature of https://log4sure.com does allow you to monitor your client side logs realtime. You would have to setup and do the logs appropriately as you would do for tailing, but you can see all the logs with extra information about your client, example browser, os, country etc. You can also create your own custom logs to log stuff. Checkout the demo on the site to get a better idea.
The setup code is really easy, and the best part is, its free.
// set up
var _logServer;
(function() {
var ls = document.createElement('script');
ls.type = 'text/javascript';
ls.async = true;
ls.src = 'https://log4sure.com/ScriptsExt/log4sure-0.1.min.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ls, s);
ls.onload = function() {
// use your token here.
_logServer = new LogServer("use-your-token-here");
};
})();
// example for logging text
_logServer.logText("your log message goes here.")
// example for logging error
divide = function(numerator, divisor) {
try {
if (parseFloat(value) && parseFloat(divisor)) {
throw new TypeError("Invalid input", "myfile.js", 12, {
value: value,
divisor: divisor
});
} else {
if (divisor == 0) {
throw new RangeError("Divide by 0", "myfile.js", 15, {
value: value,
divisor: divisor
});
}
}
} catch (e) {
_logServer.logError(e.name, e.message, e.stack);
}
}
// another use of logError in window.onerror
// must be careful with window.onerror as you might be overwriting some one else's window.onerror functionality
// also someone else can overwrite window.onerror.
window.onerror = function(msg, url, line, column, err) {
// may want to check if url belongs to your javascript file
var data = {
url: url,
line: line,
column: column,
}
_logServer.logError(err.name, err.message, err.stack, data);
};
//example for custom logs
var foo = "some variable value";
var bar = "another variable value";
var flag = "false";
var temp = "yet another variable value";
_logServer.log(foo, bar, flag, temp);
While I wish it had better JSON object prettification for live tailing and historical logs, the following JS client works and supports your server-side requirement also:
https://github.com/logentries/le_js/wiki/API
<html lang="en">
<head>
<title>Your page</title>
<script src="/js/le.min.js"></script>
<script>
// Set up le.js
LE.init('YOUR-LOG-TOKEN');
</script>
</head>
.....
<script>
// log something
LE.log("Hello, logger!");
</script>
Personally to get the above code to work however, I've had to add the following line of code just above LE.init('YOUR-LOG-TOKEN'):
window.LEENDPOINT = 'js.logentries.com/v1'
.. Alternatively, Loggly may be a fit as well: https://www.loggly.com/docs/javascript/
I have the following code:
var stressWorker = new Worker("./test/webworkers/worker.js");
stressWorker.onmessage = function(event){
alert(event.data);
};
stressWorker.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
worker.js:
onmessage = function(e){
postMessage("test");
}
The script finds the 'worker.js' file but it doesn't actually run it. What am I doing wrong?
PS. I'm hosting both scripts using wamp and I'm using chrome
worker.js won't do anything until it receives a message. I can't see where you are sending it a message. You need something like stressWorker.postMessage(...) somewhere.
Are you sure your browser supports this particular HTML5 feature?
This article has many ways to test for support of each feature. The test for Worker is
return !!window.Worker;
Edit: As I see it, there's either a problem with your code or it can't find the file. Your code looks a lot like this example except there the .js file code is like this, with the self:
self.onmessage = function(e) {
self.postMessage("Hello " + e.data);
};
It should be easy enough for you to try that and see if it's the missing piece here.
One main thing You should remember If you are running scripts on same origin and using chrome, you should start the chrome with the flag --allow-file-access-from-files or You should run app on local server.
See the code
var stressWorker = new Worker("../test/webworkers/worker.js");
stressWorker.onmessage = function(event){
alert(event.data);
};
stressWorker.postMessage("Hello there");
stressWorker.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
Now you will get The response from the worker. ".." I suspect path is wrong.