Cara menggunakan find unused css vscode

So I've set up vscode with Prettier, but it will not format .php files. .html files are working fine with Prettier. So when I have a .php with HTML code then it will be formatted differently, because I am using Beautify as last option.

How can I make Prettier automatically format .php files and the html code in .php the same as .html files?

settings.json

{
  "sync.autoDownload": true,
  "sync.autoUpload": true,
  "sync.forceDownload": true,
  "sync.forceUpload": true,
  "workbench.iconTheme": "vscode-icons",
  "sync.gist": "715bf022af486e449cae9313183b9a56",
  "sync.quietSync": true,
  "typescript.updateImportsOnFileMove.enabled": "always",
  "window.zoomLevel": 0,
  "vetur.format.defaultFormatter.js": "vscode-typescript",
  "vetur.format.defaultFormatter.ts": "vscode-typescript",
  "eslint.codeActionsOnSave.mode": "all",
  "workbench.colorTheme": "Atom One Dark",
  "beautify.language": {
    "html": ["php", "blade"]
  },
  // These are all my auto-save configs
  "editor.formatOnSave": true,
  // turn it off for JS and JSX, we will do this via eslint
  "[javascript]": {
    "editor.formatOnSave": false
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false
  },
  // tell the ESLint plugin to run on save
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  },
  // Optional BUT IMPORTANT: If you have the prettier extension enabled for other languages like CSS and HTML, turn it off for JS since we are doing it through Eslint already
  "prettier.disableLanguages": ["javascript", "javascriptreact"],
  "php.validate.executablePath": "C:\\xampp\\php\\php.exe"
}

.eslintrc.json

{
  "extends": ["airbnb", "prettier", "prettier/react"],
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 2020,
    // Can I remove these now?
    "ecmaFeatures": {
      "impliedStrict": true,
      "classes": true
    }
  },
  "env": {
    "browser": true,
    "node": true,
    "jquery": true,
    "jest": true
  },
  "rules": {
    "no-debugger": 0,
    "no-alert": 0,
    "no-await-in-loop": 0,
    "no-return-assign": ["error", "except-parens"],
    "no-restricted-syntax": [
      2,
      "ForInStatement",
      "LabeledStatement",
      "WithStatement"
    ],
    "no-unused-vars": [
      1,
      {
        "ignoreSiblings": true,
        "argsIgnorePattern": "res|next|^err"
      }
    ],
    "prefer-const": [
      "error",
      {
        "destructuring": "all"
      }
    ],
    "arrow-body-style": [2, "as-needed"],
    "no-unused-expressions": [
      2,
      {
        "allowTaggedTemplates": true
      }
    ],
    "no-param-reassign": [
      2,
      {
        "props": false
      }
    ],
    "no-console": 0,
    "import/prefer-default-export": 0,
    "import": 0,
    "func-names": 0,
    "space-before-function-paren": 0,
    "comma-dangle": 0,
    "max-len": 0,
    "import/extensions": 0,
    "no-underscore-dangle": 0,
    "consistent-return": 0,
    "react/display-name": 1,
    "react/no-array-index-key": 0,
    "react/react-in-jsx-scope": 0,
    "react/prefer-stateless-function": 0,
    "react/forbid-prop-types": 0,
    "react/no-unescaped-entities": 0,
    "jsx-a11y/accessible-emoji": 0,
    "react/require-default-props": 0,
    "react/jsx-filename-extension": [
      1,
      {
        "extensions": [".js", ".jsx"]
      }
    ],
    "radix": 0,
    "no-shadow": [
      2,
      {
        "hoist": "all",
        "allow": ["resolve", "reject", "done", "next", "err", "error"]
      }
    ],
    "quotes": [
      2,
      "single",
      {
        "avoidEscape": true,
        "allowTemplateLiterals": true
      }
    ],
    "prettier/prettier": [
      "error",
      {
        "trailingComma": "es5",
        "singleQuote": true,
        "printWidth": 80
      }
    ],
    "jsx-a11y/href-no-hash": "off",
    "jsx-a11y/anchor-is-valid": [
      "warn",
      {
        "aspects": ["invalidHref"]
      }
    ],
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn"
  },
  "plugins": ["html", "prettier", "react-hooks"]
}

When you visit a web page, your browser requests all of the resources it needs to build it. Often a page will end up loading resources, such as JavaScript and CSS, containing code that isn’t actually needed to build the page in question; as a result, page load speed increases needlessly.

Most code is processed and loaded in the browser through what is known as the main thread. Think of it as a single-lane, one-way road. Each resource is a single car driving down that road, all of which have to arrive at their destination — the browser — for the page to finish loading. The more code you are trying to process, the longer it will take to finish loading the page. JavaScript and CSS typically take the most time to parse, compile and execute. Additionally, user interactions also run on that main thread. This means that the longer that JavaScript or CSS take to execute, the longer the page remains unresponsive to user interactions, leading to a less-than-satisfactory user experience.

With Page Experience (notably , for the purposes of this discussion) being taken into account by Google’s algorithms for ranking, it is important to make sure that you are doing everything you can to provide a good user experience, including reducing page load times and other page experience metrics such as Time to Interactive.

This guide will show how to quickly identify unused code in JavaScript and CSS resources so that you can take action, only load what is necessary, and improve your page load speeds.

Important – Before You Remove Any Code

We strongly recommend that you set up a staging environment before you publish any code alterations to your live site. JavaScript can be critical to functionality, and CSS equally as important for page structure, element visibility, and content presentation, among other things. You don’t want to accidentally remove some code that your page relies on to load properly, so it’s important to test any changes in staging before you push them live.

Always consider  the different ways a user will experience your site before you remove any code. For example, a user that is logged in may require alternate styles or JavaScript functions than a user that is logged out. Another thing to be particularly conscious of is device-specific CSS. Media queries can be used to define styles for elements depending on specific viewport breakpoints. Some tools or automated programs for finding unused code may not take this into consideration and could falsely declare a currently inactive style as unused.

Always back up and test thoroughly before deploying any code changes.

Start with a Plugin Audit

An easy place to start looking for unnecessary code is in plugins and extensions.

While plugins can be useful for content management and other rich site features, they do often load unnecessary code across pages of your entire site. Take the very popular Contact Form 7, for example. It loads code on every single post and page of your WordPress site, regardless of whether or not those pages contain a contact form.

In many cases, site owners use plugins to solve a single problem, but often install a bloated plugin overloaded with unneeded features that aren’t relevant to the problem at hand. This is problematic because even though features aren’t being used, the JavaScript library or libraries required to use them may still be loading in the background of your pages.

Use Plugins Judiciously

Take time to review all of the plugins and extensions that are being used on your site. Evaluate whether a plugin is absolutely required. If you are using a plugin for a single specific feature, try searching for another plugin that does just that. You’ll be surprised at how many lightweight add-ons out there provide straightforward, simple solutions without any extra features. Always use the official repositories for any CMS:

  • WordPress Plugins
  • Shopify App Store
  • Magento Extensions
  • Joomla Extensions
  • Squarespace Extensions

Alternatively, consider working with a developer to help you consolidate and incorporate specific features into your site’s architecture/CMS without a plugin. For example, Google Tag Manager and Google Analytics can be installed into your site template with some simple code. Yet there are entire plugins designed to help make the code implementation easier, often with additional, unnecessary code attached to them.

A good time to review your plugins is after a site launch. Plugins will often be installed for debugging or importing/exporting purposes, and may be fine to remove once the updated site is live. You may also find that there are plugins you use, but only occasionally, so consider deactivating those until you really need them to be active.

How To Find Unused CSS & JavaScript

Most popular browsers have inspector panels that display the network requests being sent to load that page. This can help you understand what JavaScript and CSS resources are being loaded on any given page. Here are links to documentation on how to locate and see the network activity on each of the following browsers:

  • Chrome
  • Firefox
  • Safari
  • Microsoft Edge

It is important to note that you cannot remove unused code from resources that are not hosted by your domain. However, with resources that you do host, you should be able to optimize.

How to Use Chrome DevTools to Find Unused Code

One of the great features of Chrome DevTools is the ability to see unused CSS and JavaScript in real time. This approach may not be useful at scale, but it can help you quickly identify the resources that contain unused code on an individual page.

Cara menggunakan find unused css vscode

When you visit a URL, the Coverage tab will tell you how much code was used, versus how much was loaded, from any given resource.

To open Chrome DevTools, press Ctrl + Shift + I or click the right mouse button and choose Inspect. 

To see it yourself:

  1. Open Chrome Developers Tools (press Ctrl + Shift + I or click the right mouse button and choose Inspect.)
  2. Next, click the settings icon > More tools > Coverage
  3. After that, click the Reload button (the circle arrow icon).
  4. Filter the list that appears to only see JavaScript or CSS resources.
  5. Click any resource to see the used and unused code.

Each line of code is color-coded to help you identify used and unused code:

  • Solid green means that line of code is executed.
  • Solid red means it did not execute.

How To Use The Coverage Tab

Here’s how we used it to identify the resources that contained the most unused code to help us prioritize which to address first.

Cara menggunakan find unused css vscode

In the screenshot above you can see many CSS resources containing almost entirely unused styles. One of the items listed above is a Font Awesome CSS file. Within the DevTools Coverage tab we can drill down even further to see specifically which code/styles are unused.

The site in question used five icons in total. But the CSS file loaded thousands of icon styles on every single page and post.

Cara menggunakan find unused css vscode

Right away we know that we could specifically extract the icon styles the site needed and load only those instead. This required updating all of the file paths pointing to the current file with a path to the new, much smaller file we made.

How To Remove Unused CSS & JavaScript

There is no denying that removing unused CSS or JavaScript is a challenging, time-consuming task. It will take a lot of patience and testing.

Always look for the biggest opportunities to remove anything that is outright unnecessary (such as the plugin audit suggested above) first. In most cases, CSS is more lightweight than JavaScript so look for CSS-only alternatives to replace JavaScript features that you may be using across your site.

Consider an Automated Service

While removing CSS and JavaScript from smaller sites is manageable, it can be daunting for large sites. Fortunately there are reasonably-priced services that can automate the removal process.

As with almost any automated service, take caution. Be sure to back up your site, and test thoroughly on a staging environment. Here are a few automated services to consider:

  • UnusedCSS
  • PurifyCSS Online 
  • UnCSS Online 

Use a Plugin

I know that this seems like a hypocritical recommendation, but if you’re looking for a more cost-effective solution than an automated service,  you might consider using a plugin. Ideally, the page load time you’ll be saving by removing unneeded resources will more than make up for the load represented by the additional plugin.

Perfmatters Script Manager springs to mind as an option for WordPress. It allows you to disable entire plugins, queries, and inline CSS/JS – even external scripts if they are enqueued properly in WordPress. Not to mention, the plugin also allows you to add exceptions based on whether a user is logged in or logged out.

Bundle Resources and Deliver Them Efficiently

While removing unnecessary plugins and unused code will help overall, bundling and delivering only the resources a given page needs can also make a significant impact.

With bundling, you will reduce the number and size of network requests, alleviating the amount of work processed on the main thread.

To do that, we recommend building a common bundle with code that every page uses, and then template-specific bundles on top of that. For example, on WordPress you could create CSS and JavaScript bundles specifically for posts, for pages, and for the home page. If you have an ecommerce site you can create bundles for product pages, categories, and even the checkout process.

Going a step further, you can even separate JavaScript and CSS into critical bundles. Instead of attempting to load everything as soon as a user arrives at the page, you can split your bundles to only deliver your most critical code first. This is known as code splitting and would require help from an experienced developer. Here’s a good overview on how you can determine critical CSS, and a tool (criticalcss.com) that helps you generate critical CSS files for any URL. As always, be sure to test any automated process.

Once you have a good understanding of which resources are required for specific page types you can bundle them together and deliver them accordingly. 

Stay mindful of the bundle file size. Bundling everything into a large single file can still increase load times on the main thread. Find a good balance between the number of bundles and the size of each bundle. As a rule of thumb, each bundle should be around 100 kB. In addition to removing unused CSS and JavaScript, ensure that your files are minified to help you achieve even smaller bundles.

What is Minification?

Minification refers to the process of removing unnecessary or redundant data without affecting how the resource is processed by the browser, e.g. by deleting code comments and formatting, deleting obsolete code, using shorter variable and function names, and so on. HTML, CSS, and JavaScript resources should always be kept as slim as possible to speed load times.

Most hosting services provide minification services, but if you wanted to get a little more hands on experience, here are some recommendations you could explore:

  • To minify HTML, try HTMLMinifier.
  • To minify CSS, try CSSNano and csso.
  • To minify JavaScript, try UglifyJS. The Closure Compiler is also ; a build process can be created which will use these tools to minify and rename development files and save them to a production directory.

Google’s own PageSpeed Module also integrates with an Apache or nginx web server to automatically optimize a whole site for performance, including resource minification.

Take Your Time

Of all the aspects to performance optimization, cleaning up and removing unused code is one that can have a noticeable effect. If done well your pages will run efficiently, and will undoubtedly provide a pleasant experience for your users – which is important to Google, and more importantly your bottom line.

Just remember to take your time and test thoroughly before pushing anything live. If you have additional recommendations for a plugin, resource or service. Do let us know in the comments, we’d love to hear about it!