Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Como corrigir JavaScript e CSS de bloqueio de renderização no WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Você está tentando eliminar o JavaScript e o CSS que bloqueiam a renderização no WordPress?

Se você testar seu site no Google PageSpeed Insights, provavelmente verá uma sugestão para eliminar scripts e CSS que bloqueiam a renderização. No entanto, ele não fornece nenhum detalhe sobre como fazer isso em seu site WordPress.

Neste artigo, mostraremos como corrigir facilmente o JavaScript e o CSS que bloqueiam a renderização no WordPress para melhorar sua pontuação no Google PageSpeed.

How to fix render blocking JavaScript and CSS in WordPress

O que é JavaScript e CSS de bloqueio de renderização?

JavaScript e CSS de bloqueio de renderização são arquivos que impedem que um site exiba uma página da Web antes de carregar esses arquivos.

Todo site WordPress tem um tema e plug-ins que adicionam arquivos JavaScript e CSS ao front-end do seu site.

Esses scripts podem aumentar o tempo de carregamento da página do seu site e também podem bloquear a renderização da página.

Render blocking issue highlighted in Google Pagespeed Insights

O navegador do usuário terá que carregar esses scripts e CSS antes de carregar o restante do HTML na página. Isso significa que os usuários com uma conexão mais lenta terão que esperar alguns milissegundos a mais para ver a página.

Esses scripts e folhas de estilo são chamados de JavaScript e CSS de bloqueio de renderização.

Os proprietários desites WordPress que estão tentando obter uma pontuação de 100 no Google PageSpeed precisarão corrigir esse problema para obter essa pontuação perfeita.

O que é um Google PageSpeed Score?

O Google PageSpeed Insights é uma ferramenta de teste de velocidade de sites criada pelo Google para ajudar os proprietários de sites a otimizar e testar seus sites. Essa ferramenta testa seu site de acordo com as diretrizes de velocidade do Google e oferece sugestões para melhorar o tempo de carregamento da página.

Ele mostra uma pontuação com base no número de auditorias em que seu site foi aprovado. A maioria dos sites obtém uma pontuação entre 50 e 70. Entretanto, alguns proprietários de sites se sentem compelidos a atingir 100 (a pontuação mais alta que uma página pode obter).

Você realmente precisa da pontuação perfeita de “100” do Google PageSpeed?

O objetivo dos insights do Google PageSpeed é fornecer diretrizes para melhorar a velocidade e o desempenho do seu site. Você não é obrigado a seguir essas regras rigorosamente.

Lembre-se de que a velocidade é apenas uma das muitas métricas de otimização de mecanismos de busca (SEO) de sites que ajudam o Google a determinar como classificar seu site. A velocidade é muito importante porque melhora a experiência do usuário no seu site.

Uma melhor experiência do usuário requer muito mais do que apenas velocidade. Você também precisa oferecer informações úteis, uma interface de usuário melhor e conteúdo envolvente com texto, imagens e vídeos.

Sua meta deve ser criar um site rápido que ofereça uma ótima experiência ao usuário.

Recomendamos que você use as regras do Google PageSpeed como sugestões. Se for possível implementá-las facilmente sem prejudicar a experiência do usuário, isso é ótimo. Caso contrário, tente fazer o máximo que puder e não se preocupe com o resto.

Dito isso, vamos dar uma olhada no que você pode fazer para corrigir JavaScript e CSS que bloqueiam a renderização no WordPress.

Abordaremos dois métodos que eliminarão os recursos de bloqueio de renderização no WordPress. Você pode escolher o que funciona melhor para seu site:

Método 1: Corrigir scripts e CSS de bloqueio de renderização com o WP Rocket

Para esse método, usaremos o plugin WP Rocket. Ele é o melhor plugin de otimização e armazenamento em cache para WordPress do mercado, que permite melhorar rapidamente o desempenho do seu site sem nenhuma habilidade técnica ou configuração complicada.

Primeiro, você precisa instalar e ativar o plug-in WP Rocket. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.

WPRocket plugin

O WP Rocket funciona imediatamente e ativará o armazenamento em cache com as configurações ideais para seu site. Você pode saber mais sobre ele em nosso guia completo sobre como instalar e configurar corretamente o WP Rocket no WordPress.

Por padrão, ele não ativa as opções de otimização de JavaScript e CSS. Essas otimizações podem afetar a aparência do seu site ou alguns recursos, e é por isso que o plug-in permite que você ative essas configurações opcionalmente.

Para fazer isso, você precisa visitar a página Settings ” WP Rocket e, em seguida, alternar para a guia “File Optimization” (Otimização de arquivos).

A partir daí, role até a seção Arquivos CSS e marque as caixas ao lado de “Minify CSS”, “Combine CSS Files” e “Optimize CSS Delivery”.

CSS Optimization settings in WP Rocket

Para a configuração “Optimize CSS Delivery”, a WP Rocket recomenda escolher o método“Remove Unused CSS“.

Além de oferecer o melhor desempenho, ele pode ajudar a reduzir o tamanho da página e as solicitações HTTP.

Removing unused CSS with WP Rocket

Observação: O plug-in de cache do WP Rocket tentará reduzir todos os seus arquivos CSS, combiná-los e carregar somente o CSS necessário para a parte visível do seu site.

Isso pode afetar a aparência do seu site, portanto, é necessário testá-lo minuciosamente em vários dispositivos e tamanhos de tela.

Em seguida, role até a seção Arquivos JavaScript. A partir daqui, você pode verificar todas as opções para obter o máximo de aprimoramento do desempenho.

JavaScript optimization

Você pode reduzir e combinar arquivos JavaScript como fez com o CSS.

Você também pode impedir o WordPress de carregar o arquivo jQuery Migrate. É um script que o WordPress carrega para fornecer compatibilidade para plug-ins e temas que usam versões antigas do jQuery.

A maioria dos sites não precisa desse arquivo, mas ainda assim você deve verificar seu site para garantir que a remoção dele não afete o tema ou os plug-ins.

Em seguida, role a tela para baixo um pouco mais e marque as caixas ao lado das opções “Carregar JavaScript diferido” e “Modo de segurança para jQuery”.

Optimize JavaScript delivery

Essas opções atrasam o carregamento de JavaScripts não essenciais, e o modo de segurança do jQuery permite que você carregue o jQuery para temas que possam usá-lo em linha. Você pode deixar essa opção desmarcada se tiver certeza de que seu tema não usa jQuery embutido em nenhum lugar.

Não se esqueça de clicar no botão “Save Changes” (Salvar alterações) para armazenar suas configurações.

Depois disso, talvez você também queira limpar o cache no WP Rocket antes de testar seu site novamente com o Google PageSpeed Insights.

Em nosso site de teste, conseguimos atingir uma pontuação de 100% em dispositivos desktop, e o problema de bloqueio de renderização foi resolvido nas pontuações de dispositivos móveis e desktop.

Fixed render-blocking issue to achieve perfect page speed score

Método 2: Corrigir scripts e CSS que bloqueiam a renderização com o Autoptimize

Para esse método, usaremos um plugin separado, criado especificamente para melhorar a entrega dos arquivos CSS e JS do seu site. Embora esse plug-in faça o trabalho, ele não tem os outros recursos avançados que o WP Rocket tem.

A primeira coisa que você precisa fazer é instalar e ativar o Autoptimize, um plug-in gratuito para acelerar o desempenho do site. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.

Após a ativação, você precisa visitar a página Settings ” Autoptimize para definir as configurações do plug-in.

Primeiro, você precisa marcar a caixa ao lado de “Otimizar código JavaScript” no bloco Opções de JavaScript. Certifique-se de que a opção “Aggregate JS-files” esteja desmarcada.

Optimize JS files in Autoptimize

Em seguida, role para baixo até a caixa Opções de CSS e marque a opção “Otimizar código CSS”.

Certifique-se de que a opção “Aggregate CSS-files” (Agregar arquivos CSS) esteja desmarcada.

Optimize CSS in Autoptimize

Agora você pode clicar no botão “Save Changes and Empty Cache” para armazenar suas configurações.

Vá em frente e teste seu site com a ferramenta PageSpeed Insights. Em nosso site de demonstração, conseguimos corrigir o problema de bloqueio de renderização com essas configurações básicas.

Fixed render blocking issue in WordPress with Autoptimize plugin

Se ainda houver scripts de bloqueio de renderização, você poderá voltar à página de configurações do plug-in e revisar as configurações nas opções JavaScript e CSS.

Por exemplo, você pode permitir que o plug-in inclua JS em linha e remova os scripts excluídos por padrão, como seal.js ou jquery.js. Em seguida, basta clicar no botão “Save changes and Empty Cache” para salvar suas alterações e esvaziar o cache do plug-in.

Quando terminar, verifique seu site novamente com a ferramenta PageSpeed Insights.

Como funciona o Autoptimize?

O Autoptimize agrega todos os JavaScript e CSS enfileirados. Depois disso, ele cria arquivos CSS e JavaScript minificados e fornece cópias em cache para seu site como assíncrono ou diferido.

Isso permite que você corrija o problema de scripts e estilos de bloqueio de renderização. No entanto, lembre-se de que isso também pode afetar o desempenho ou a aparência do seu site.

O que fazer se o JavaScript e o CSS que bloqueiam a renderização ainda existirem

Dependendo de como os plug-ins e o tema do WordPress usam JavaScript e CSS, pode ser difícil corrigir completamente todos os problemas de JavaScript e CSS que bloqueiam a renderização.

Embora as ferramentas acima possam ajudar, seus plug-ins podem precisar de determinados scripts em um nível de prioridade diferente para funcionar corretamente. Nesse caso, as soluções acima podem interromper a funcionalidade desses plug-ins ou eles podem se comportar de forma inesperada.

Em vez de tentar eliminar completamente os problemas de bloqueio de renderização, recomendamos adotar abordagens alternativas para acelerar seu site. Por exemplo, você pode usar um serviço de CDN para servir seus arquivos estáticos de JavaScript e CSS e reduzir o tempo de carregamento.

Você pode ler nosso guia definitivo para aumentar a velocidade e o desempenho do WordPress para obter mais informações.

Esperamos que este artigo tenha ajudado você a aprender como corrigir JavaScript e CSS que bloqueiam a renderização no WordPress. Talvez você também queira ver nosso artigo sobre como o WPBeginner aumenta a velocidade de carregamento da página com 6 dicas e nossa comparação das melhores empresas de hospedagem gerenciada do WordPress.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

81 ComentáriosDeixe uma resposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Jiří Vaněk says

    I use autoptimize and also wp-rocket. It helped me tremendously. However, it is necessary to be very careful with some changes. One setting and the entire website can immediately stop working correctly.

  3. Amina says

    Hello there, your site and tips have really been helpful. Thank you wpbeginner!

    My AMP says customize JavaScript script not allowed. I have tried using and followed your instructions for autoptimize but it didn’t solve the problem. The amp shows the error is in line 12:10 and 18:2.

    • WPBeginner Support says

      Glad our article was helpful, for AMP specific questions like that we would recommend reaching out to AMP’s support and they should be able to assist.

      Administrador

    • WPBeginner Support says

      There are likely other tools but these are the current ones we recommend for beginners.

      Administrador

  4. Rizz says

    For W3 Total cache users
    Dont add jquery Script (/wp-includes/js/jquery/jquery.js?ver=1.12.4-wp) It will work otherwise your site will not load properly.
    Css will not through any error

    If Revolution silder will post an error after it –> go to revslider global settings and turn on Insert scripts in footer.

  5. Muhammad Farhan says

    I don’t remember when ever i find myself struck in a difficult position, you are always there to help me when no body is around i don’t know of any best site of wordpress guide than wpbeginners, thank you so much

  6. Lu says

    Great info as always!

    I’m with Siteground so have SG Optimizer on my site. I’ve gone through the settings as much as I understand, but still getting the Eliminate render-blocking resources.

    Can I use Autoptimize as well, or will it clash with SG? Thanks

    • WPBeginner Support says

      You should be able to use Autoptimize with SG Optimizer but if you have any concerns if you reach out to the plugin’s support they should be able to let you know if there are currently any conflicts between the two :)

      Administrador

    • WPBeginner Support says

      You would need to manually go through the code and set the CSS and JS files to load after the content is added to the page.

      Administrador

  7. MoneyManch says

    Hi WP Beginner Team,

    Thanks a lot for sharing such a useful article. Autoptimize is an awesome plugin.

    I was looking for a plugin to boost the speed of my wp blog. After reading this post, I installed and activated “Autoptimize” on my blog. And to my surprise it increased the speed of my blog from 39 to 61 for mobile and 76 to 95 for desktop checked on PageSpeed Insights.

    Thank once again for guiding new bloggers like me.

    • WPBeginner Support says

      If you use Google Page insights then there is a dropdown arrow which will show you the URLs that are causing the problem with a learn more link for how to find the url without their tool.

      Administrador

    • WPBeginner Support says

      There should be a dropdown arrow and when you click that it should show the links to the files :)

      Administrador

  8. Deeksha says

    When I use all these plugins suddenly my website go slow down & it shows inappropriate content…
    What Can I Do ?? Please Help

    • WPBeginner Support says

      Hi Deeksha,

      Both plugins are quite safe. If you are seeing inappropriate content on your website, then please make sure that your website is not hacked. You can disable both plugins at any time.

      Administrador

  9. sumit kumar gupta says

    Sir When we install Autoptimize plugin in our WordPress blog then our blog is not opening it says this page is not working. What should I do Sir?

    Sir I would like to know when we add javascript link to eliminate render blocking code following by your steps then any affect is occuring on my blog ranking. please help

    • Tim Helmer says

      Sumit:

      The plugin is not working so you need to rename the plugin folder to turn it off. You need ftp or a file manager plugin. Can you access the dashboard via your wp-login.php location? Like domain/wp-login.php

  10. Henry Ramirez says

    I use wordpress.com, any plugin to do the same thing here on wordpress.com since this plugins are no supported here? Thanks

  11. Ismail says

    Hello,
    Currently I am using WP Rocket, is it possible to use Autoptimize plugin together? Thanks for sharing this valuable information.

  12. Gaurav Areng Chakraverti says

    Hi there. I’ve tried the W3 method and as soon as I turn on Minify (using Disk) I get this:
    Fatal error: Unknown: Cannot use output buffering in output buffering display handlers in Unknown on line 0

    How does one fix that?

    Great tutorial though overall! Thanks for this.

    • Gaurav Areng Chakraverti says

      EDIT: This problem goes away when I deactivate Autoptimize, however, so does the rest of the site. Only the bare bones remain with no actual content. :|

  13. David says

    The settings for Autoptimize has changed. The only JavaScript Options available is Optimise JavaScript Code? The rest of the options in your screenshot is not available, at least not on the one I have. Last time I tried W3 Total Cache, nobody could access the site. I am still looking for a way of solving the load time of the page, which for some reason stand at anything from 10 – 17 seconds.

    • Chris says

      David, try Gmetrix web speed tool. On the results list there is a waterfall chart showing how the site loads and what the largest files and scripts slowing the page load.
      I find the slowest scripts are googles cdn scripts like google fonts! The very same company insisting, forcing users to their demands have to scripts taking an age to load. You couldn’t make it up.

  14. Divij says

    Can you use minify on w3 total cache simultaneously with cloudflare? We are using minify in cloudflare and left it disabled in w3cache. But we still keep getting the message- Eliminate render-blocking JavaScript and CSS in above-the-fold content.

    Thanks!

  15. Rana Jayant says

    The plugin 23 cache UI has been changed and it doesn’t have any option where we can put our .js URL for optmization.
    I am talking about “Now head over to your WordPress admin area and go to Performance » Minify page.”

  16. MATTY says

    Great tutorial. However is W3 Total cache safe to use now due to an issue earlier in the year? I’ve stopped using it since but it was the best plugin out there.

  17. Mohamed says

    Thanks for sharing this article but you said (please keep in mind that it can also affect the performance or appearance of your website)
    Please clarify if this effect will be good or bad for the website google ranking?

    • WPBeginner Support says

      Hi Mohamed,

      A faster website is certainly good for SEO rankings. However, when fixing render blocking issues you may end up changing appearance of your theme or get even a lower page speed score than before.

      Administrador

  18. Angie says

    Ha, funny.

    I was looking for help here.
    then I did the google speed tool for YOUR post here.

    Google result

    mobile Poor
    54 / 100

    desktop
    Needs Work
    66 / 100

    Do you have any clue at all?

  19. Chris Daly says

    Every single time I use Autoptimize or W# Total Cache my site explodes. The mobile web view gets trashed into an html menu list and parts of the site stop working. I have tried each of these on 4 different sites and dropped both of them.

    • Chris says

      Chris I suggest you read and adhere to the W3 Cache warning on the minify section. Minify html and css only and again be wary not all css should be mini-fied due to the reasons stated in the post above.
      I use W3 Cache selectively, tinyjpg for image optimisation, and set OpCache in the .htaccess file. Templaters love to use Sliders…but they bloat the page with images screen width at 1920pxs. Ditch the sliders, smaller images (with a modal box if greater detail required) and icons instead.

  20. Bruno Ayres Martinez says

    Hey guys! I’ve loved the W3 tutorial. There’s just one information missing: The Embed Location for the JS File Management.

    Is it “Embed before Body”? Or “embed in Head”? Or “Embed after Body”?

  21. Dev thapa says

    I am new to Blogging, however, I have been following Wpbeginner.com for quite sometime and whatever they are writing I found them very useful and don’t hesitate to say that, today if my blog page is Live…30% credit goes to Wpbeginner.com team and Sayed Balkhi for creating such a wonderful and useful webpage.
    I am thankful to Wpbeginner.
    Keep it up, all the best.

  22. Digember says

    Plugins increase loads on our website which makes our site slow. At wpbeginner, I haven’t seen a single method of speed optimization without the use of plugins. Teach us something useful, these methods don’t work for everyone.

  23. Patricia Lynn says

    Great detailed information on using Autoptimize plugin dealing with Java-scrip, CSS and plugin w3 Total Cashe to fix render blocking while enhancing website speed performance

  24. Sumit yadav says

    Thanks a lot for this information. Earlier my page loading load time speed was 63 and after installing Autoptimize plugin it increases to 81.

    • Yoseph says

      I am not very sure what happen, I installed autoptimize in one of my site, then the page size increase from 2.8mb to 4mb

  25. Erez Elias says

    Thanks for sharing.
    Overall the speed of the site increased by very little. But the issue with render blocking is not resolved.

    Comment if you have other suggestions.

    thanks.

  26. David says

    I got 3 new websites down to almost 500 ms, faster than 96% of sites on Pingdom. Similar for other speed testers.

    Thought great, till Google brought me back down to earth with their page insights. Mainly low score for mobile, but thought these modern themes are meant to be responsive? Obviously not!

    I squeezed every image down to next to nothing before uploading as well, so it is frustrating.

    Also, none of the apps work for me with Browser Cache, etc.

    I’d say the same three problems I have – once the basics are done – are:
    1. Render blocking Javascript.
    2. Browser caching.
    3. Images wrong size for mobile.

  27. Michael says

    I’m a bit confused. I just ran a Google speed test on wpbeginner and if didn’t score well at at all. What am I missing?

  28. Manohar Rao says

    Both Autoptimize and W3 Total cache plugins have damaged my website. These plugins works with certain themes only. One has to be very careful to use these two plugins.

  29. Toby Forage says

    When I installed Autoptimize, as suggested in this article, it completely screwed up my website. Maybe I set it up wrong, but after removing it entirely, I reached a Google PageSpeed score of 92 for desktop. Mobile is at 67, so I’m working on improving that, but won’t be using Autoptimize again, that’s for sure!

  30. Fued says

    Hi WP beginner,

    Very helpful article!
    Thank you!

    Just a random question?

    Can I set it back minified mode from manual to auto and delete the minified files without harm? And what do you recommend: manual or auto?

    Cheers

  31. ibraheem Warriach says

    Hi i Liked article butt em not getting option to add scripts in W3 Total cache plugin kindly let me know how to get that?

  32. MASI says

    Thank you very much for your great article, it’s really helped me.
    Just i have an small problem, i’m confused now!
    I added all .js and .css manually on W3TC, but still one .css has problem on google page checker:

    Consider Fixing:

    None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

    Optimize CSS Delivery of the following:

    26952.default.include.c9d602.css is available currently on .css list, but i see this error. How can i fix this problem?

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.