- Обрабатываем блокирующий рендеринг CSS для ускорения рендеринга сайта
- Проблема: CSS блокирует рендеринг
- Концепция критического CSS
- Используйте медиа типы и медиа запросы для минимизации блокировок рендеринга
- How to Fix CSS when It’s Not Working in Google Chrome
- Why is my CSS not working in Chrome?
- Opera One
- What can I do if CSS doesn’t work in Chrome?
- 1. Update Chrome
- 2. Clear cache and cookies
- 3. Disable problematic extensions
- 4. Check if the web server has a problem or not (for designers/developers)
- 5. Correct CSS encoding and format (for designers)
- 6. Disable CSS minification and lazy loading (For developers)
- 7. Try a different network
- What to do if CSS is not working in Chrome but works in other browsers?
- Почему с браузера Chrome не отображается стили CSS ( хотя Opera их видит)?
- Войдите, чтобы написать ответ
- Как сделать автогенерацию поддомена?
Обрабатываем блокирующий рендеринг CSS для ускорения рендеринга сайта
От автора: я все время думала, что вопрос, когда и как загружать CSS-файлы, лучше оставить самому браузеру. Браузеры спроектированы для работы с такими вещами. Зачем разработчикам что-то делать, если можно просто добавить ссылку с rel=»stylesheet» и href=»style.css» в head документа и забыть?
По-видимому, сегодня этого уже не достаточно, по крайней мере, если вы думаете о скорости сайта и быстром рендеринге страниц. Учитывая, как эти два фактора влияют на UX и успех сайта, скорее всего, вы уже искали способы контролировать метод загрузки стилей в браузере по умолчанию.
В этой статье я расскажу о том, что может пойти не так, когда браузеры загружают CSS-файлы, а также мы обсудим возможные подходы к проблеме, которые вы испытаете на своем сайте.
Проблема: CSS блокирует рендеринг
Если вы хоть раз пользовались Google Page Speed Insights для проверки производительности сайта, вы должны были встречать сообщения подобного содержания:
Онлайн курс «Веб-разработчик с нуля до PRO»
Изучите курс и разработайте полноценную CRM-систему управления контактными данными клиентов
Вы научитесь верстать сайты на HTML и CSS, изучите JavaScript. Сможете разрабатывать на PHP серверную часть сайта — и сделаете первые проекты для портфолио.
Google Page Insights описывает проблему и предлагает стратегию ее решения.
Сначала давайте попробуем лучше понять суть проблемы.
Для отображения веб-страниц браузеры используют DOM (Document Object Model) и CSSOM (CSS Object Model). DOM – модель HTML, необходимая браузеру для рендеринга структуры страницы и ее контента. CSSOM – карта CSS, которую использует браузер для стилизации веб-страниц.
CSS является частью критического пути рендеринга, т.е. браузер тормозит рендеринг веб-страницы до тех пор, пока не загрузятся и обработаются все HTML и CSS файлы. Это объясняет, почему HTML и CSS файлы считаются блокирующими рендеринг файлами. Внешние стили включают в себя многократные запросы туда-обратно между браузером и сервером. Это может вызывать задержку между временем загрузки HTML и временем рендеринга страницы на экран.
Проблема заключается в этой задержке, когда пользователь смотрит на пустой экран несколько миллисекунд. Не самый лучший опыт от первого посещения сайта.
Концепция критического CSS
С одной стороны, HTML в первую очередь влияет на рендеринг страницы, но в противном случае вообще нечего было бы рендерить. Можно ли то же самое сказать про CSS?
Конечно, страница без стилей совсем не user friendly, а значит, браузеру нужно подождать загрузки и парсинга CSS перед рендерингом страницы. С другой стороны, можно сказать, что не все стили критичны для построения нормальной страницы. В первую очередь пользователей интересует верхняя часть страницы, видимая на экране после загрузки без прокрутки.
За этой мыслью кроется доминирующий на сегодня подход по решению нашей проблемы и предложения из сообщения Google Page Insights. Что нас интересует: «Попробуйте отложить загрузку блокирующих ресурсов или делайте это асинхронно, или же встройте критические части ресурсов напрямую в HTML.»
Но как отложить загрузку стилей на странице или сделать ее асинхронной?
Все не так просто, как может звучать. Здесь не получится добавить атрибут toss к тегу link, как это можно было в script.
Ниже описано несколько методов, которыми разработчики решают эту задачу.
Используйте медиа типы и медиа запросы для минимизации блокировок рендеринга
Ilya Grigorik иллюстрирует простой способ минимизации блокировок рендеринга страницы, который делится на два этапа:
необходимо разбить внешний CSS на несколько файлов по медиа типам и медиа запросам, тем самым избегая загрузки больших CSS-документов;
необходимо ссылаться на все файлы с подходящим медиа типом и медиа запросом внутри тега link. Это предотвращает блокировку некоторых файлов стилей, если не соблюдаются условия медиа типа и медиа запроса.
Как пример, ссылки на внешние CSS-файлы в head документа могут выглядеть так:
How to Fix CSS when It’s Not Working in Google Chrome
Hasibul Kabir is a Tech-Enthusiast Blogger, Web Developer & Hobbyist Game Developer. Writing about Technology, mainly Windows, Mac, iOS, etc., is his main focus, besides doing some computer. read more
After moving away from the corporate work-style, Alex has found rewards in a lifestyle of constant analysis, team coordination and pestering his colleagues. Holding an MCSA Windows Server. read more
- For various reasons like different encodings, corrupted cache, networking issues, etc. CSS may not work properly on Google Chrome.
- It is not possible to enable or disable CSS without third-party extensions.
- Though updating the browser or clearing the cache may help, you will need to follow other methods mentioned in this article as well.
Try Opera One, a browser with various functionalities already built-in! A flawless browser like Opera has most functions already under the hood. Here’s what’s included by default:
- Easy and intuitive workspace management
- Ad-blocker mode integrated to load pages faster
- WhatsApp and Facebook Messenger
- Customizable Ul and AI-friendly
- ⇒ Get Opera One
Is CSS not working in Chrome? This article contains the relevant information and also the solutions to fix this problem.
The full form of CSS is Cascading Style Sheets. Without it, you would end up seeing ugly websites all over the internet. Every browser, by default, supports CSS pretty well, as this is a universal choice.
Even though Chrome is one of the best web browsers, sometimes, you may see that CSS is not working on this browser entirely or working improperly. This problem can be very repetitive and can ruin your day.
Any CSS-related issues on Chrome are equally a frustrating experience for both general users and web designers.
Why is my CSS not working in Chrome?
There may be various reasons why you are experiencing CSS problems on Google Chrome or other Chromium-based web browsers. After doing some research, we have found some common reasons. Here are they:
- The web designer used different encoding for HTML and CSS
- Corrupted cache and cookies
- Internet connection problem
- CDN server that has hosted CSS may be down or going through errors
- Third-party extensions
- Outdated version of Chrome browser
There may be other reasons. But, in most situations, these are the ones you will see.
How do I know if CSS is enabled?
- Visit any random website.
- If you see broken designs, it means Chrome is not loading the CSS.
- If you see everything looks perfect, it means Chrome is loading CSS, and it is enabled without any issues.
In Google Chrome or any modern browser, CSS is enabled by default. You cannot disable or enable this feature by yourself in the normal way.
However, some third-party extensions may disable CSS differently. In that case, you can enable or disable this feature according to the extension’s official instructions.
It may be a real nuisance to deal with CSS problems on your current browser, so won’t you consider a change?
For instance, Opera One brings enhanced navigation for advanced UI websites, integration features with popular apps and even Web3 browsing technology.
Opera One
What can I do if CSS doesn’t work in Chrome?
1. Update Chrome
- Open the Google Chrome.
- Click on three vertical dots and Settings.
- Go to About Chrome.
- Google will check for the update and install if any update is available.
- Relaunch Chrome.
2. Clear cache and cookies
- Launch Google Chrome.
- Press CTRL + Shift + Del on your keyboard.
- Set All time as the time range.
- Check Cache images and files and then click on Clear data.
3. Disable problematic extensions
- Type the following address in the Chrome address bar and press Enter . chrome://extensions/
- Toggle the switch off next to the extensions you want to disable.
4. Check if the web server has a problem or not (for designers/developers)
If a web server is going through difficulties in serving required contents like CSS and JS, the website may not load properly on any browser. In this case, if you are a webmaster, go to your web server provider’s website and see if its service is up and OK or not.
Also, if your CSS is hosted on a CDN server, the URL for the stylesheet may be like this: cdn.example.com/style.css
Some PC issues are hard to tackle, especially when it comes to missing or corrupted system files and repositories of your Windows.
Be sure to use a dedicated tool, such as Fortect, which will scan and replace your broken files with their fresh versions from its repository.
You should check that URL and see if it is accessible from your computer or not.
If not, it means the CDN server may have some problems. Take steps to solve them to fix CSS not working issues.
5. Correct CSS encoding and format (for designers)
Unlike IE, old Edge, or other non-Chromium browsers, Google Chrome handles HTML and CSS differently.
You may see that @media CSS or some CSS hyphens or CSS grid is not working in Chrome. Even in some cases, CSS color may not show up as expected.
Whether it is from a CMS like WordPress or your custom-built website, Chrome will not load CSS properly for a reason.
If your HTML and CSS are not in the same encoding format, you will see broken styling in web pages on Chrome. So, make sure formats are the same for both.
If Visual Studio Code is your editor, you can do it by following these steps:
- Open the CSS and HTML files on the editor.
- Click on the encoding format name like UTF-8 on the right-bottom side and choose the correct format.
After changing, don’t forget to save the CSS and HTML files. If you use a different editor, you may need to do it differently.
6. Disable CSS minification and lazy loading (For developers)
If you see WordPress is not loading CSS in Chrome properly, it may be because of CSS minification and combination. Try to disable it from your cache plugin. Also, disable Lazy loading and see if it helps.
7. Try a different network
If your internet connection fails to load all of the resources on a website, CSS may not work in Chrome or any other browser. So, you can try to use a VPN or a different network to check if everything is OK or not.
We suggest Private Internet Access (PIA) as it is the most stable performing VPN due to its largest global network.
Read more about this topic
What to do if CSS is not working in Chrome but works in other browsers?
This issue is very common. You may see that CSS is not working on Google Chrome, but it works on IE, Firefox, Edge, or any other browser.
The reason can be the corrupted temporary data, different CSS encoding, and a third-party Chrome extension that utilizes CSS stylesheets. The above methods are enough to solve this type of situation. You will not need to follow anything else.
This article has shown the most effective ways to fix CSS not working on Chrome and similar problems. If you know any other methods, write in the comment box.
Почему с браузера Chrome не отображается стили CSS ( хотя Opera их видит)?
Добрый вечер.
Столкнулся с, до боли странной, проблемой — Chrome не видит template.css
Хотя Opera видит.
Сайт стоит на Joomla.
Не особо понимаю из за чего может быть такая ошибка.
Оценить 3 комментария
Мистика какая то, в хроме по адресу css отображается белый экран, будто он пустой, а в опере всё норм)
В логах консоли вот что пишет
Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
data:text/html,chromewebdata:4231 /deep/ combinator is deprecated. See https://www.chromestatus.com/features/6750456638341120 for more details.
template.css:1 GET applica.com/new/new/templates/smartavi/css/template.css
applica.com/new/new/templates/smartavi/css/template.css
applica.com/new/templates/smartavi/css/template.css
IE загружает этот файл, Google Chrome считает его пустым, даже при сохранении, значит, оно так и есть. Наверное, сервер отдает файлы в зависимости от того, какой браузер он определил (но, вроде по User Agent’y всё равно не отдает в Chrom’e, наверное, какие-то другие способы).