Google PageSpeed optimization issue [duplicate] - javascript

Here is my issue.
I am analyzing my page with Google Page Speed Insights.
An it's telling me to remove my css link in the head (above floating line) because its blocking my page load.
Right now I have a simple link in the head of my document:
<link rel="stylesheet" media="all" href="http://mydomain.we/css/my.css" />
</head>
I have try to place the link line at the bottom of the document. just before the end of the page.
<link rel="stylesheet" media="all" href="http://mydomain.we/css/my.css" />
</body>
Ran Insight again.
There is 2 tabs for Insight result. By placing the css link at the en of the document I score 100% on the mobile tab. However I still get the same message on the computer part as if no mater where I place it is still getting loaded above the floating line. I don't understand because I can see the page being loaded without the css for a fraction of second.
So I'm wondering what would be the best way to load my css?
Should I place a style tag in the header?
Should I add a style tag on the elements? <-- I would rather not.
So whats the best way to load my css?
Thanks.

IMHO, Insight will always consider loading external CSS file as less efficient, because, from Google Developers - OptimizeCSSDelivery
Optimize CSS Delivery
This rule triggers when PageSpeed Insights detects that a page includes render blocking external stylesheets, which delay the time to first render.
This might be true for small CSS code, but for large ones this is not true, another disadvantage of doing this is if you decided to change something in your CSS, then you'll need to go to every single page and do the change instead of changing it one time.
Beside, external CSS files could be cached unlike inline code, also considering the webpage size will increase or each page because you included it inline in every page.
Should i add a style tag on the elements? <-- I would rather not
Never!, this will give you hard time in maintaining and generalizing your CSS, and will have the top priority so you'd bang your head against the wall wondering why changing the CSS in external file or in the head section is not taking effect.

It may be the media=all causing it because that is used to recognized all media, where as media=screen is for desktops. I would try first using media=screen and if that doesn't work try getting rid of the media tag all together.

Possible duplicate: "Eliminate render-blocking CSS in above-the-fold content"
You should be fine keeping your CSS as it is. I've never seen it suggested to link a CSS file anywhere besides the head. Google Page Insights standards doesn't mean it's the best and most optimal way, every website is different.
The fastest way would be to use <style>...</style> or even inline CSS. But that does not mean it's the best practice. If it's just a few lines of CSS, you could opt for the <style> method, but I wouldn't go out of your way if it's not appropriate just to get a perfect Google Page Insights score.

The solution for this would be first identify and separate the CSS that is used for initial page display and move it to separate file.
Load this initial css file in the head section and move the remaining css to the bottom of the page.

Related

Eliminate render-blocking resources Wordpress

I have Eliminate render-blocking resources as recommended by Google with a deferring code, but for reason the recommendation still keeps appearing on google suggestions. Any idea why?
I cleared cache*
And this is the code i have used for defer
Normally those can be removed or improved if you use caching plugins.
Also sometimes it works by moving the scripts from header to footer by using this plugin: https://wordpress.org/plugins/scripts-to-footerphp/
Firstly whatever method you found there is not a good idea. What if JavaScript is turned off in your visitors browser? They would see an unstyled page.
I find it surprising that Google would recommend this (I am guessing that is a very old article you found)??? see 'BONUS' below for a better way to defer CSS
Anyway, render blocking resources are resources that are needed to paint the 'above the fold' content. (everything you can see without scrolling when a page first loads.)
The reason your site is failing is that you are still needing to download those resources to render the initial content (if anything what you have done will slow it down I am afraid!).
To get around this is difficult as you have to inline the CSS in style tags within the document body for every item above the fold.
That way the page can be rendered without needing to wait for any external CSS files to download. -> this is what 'render blocking resources' is on about
There are plugins that are supposed to be able to do this, in my experience none of them work though as this is a complex problem to solve.
The only way to do this is to either design the theme yourself with this in mind (bit late for that) or...
Use the Google Developer Tools coverage checker (or a coverage checking tool - there are a few good ones on NPM if you can use Node), load the page and without scrolling find all the used CSS.
Then add every item of the used CSS into a <style> block within the main body of the page, then remove all the styles used from your external CSS (to save duplication, this step is not actually necessary to fix this issue).
As you will soon discover this is a nightmare to reverse engineer, but with a little patience it is possible.
Example
See the source code of klu.io (this is my site for transparency) to see how this is done, you will see there are 2 <style> blocks at the top of the page, every item in there is needed to render 'above the fold' content. (there are 2 blocks as one is site-wide and one is page specific)
Clarity on 'Above the Fold' on my site given as an example
On my site 'above the fold' is the actual visible content when the page loads as the home page is not scrollable on first load.
If you click the 'See What We Can Do For You' button you will see a load of content slides in from the right, that content is not visible so the styles for it are located in main.css.
BONUS
Also for how to defer CSS properly so it still works without JS try the following (you may need to adjust this for multiple CSS files but that is easy once you get the concept):-
<noscript id="ds">
<link rel="stylesheet" href="your-css.css" media="all">
</noscript>
JS
var dfr = function () {
var n1 = document.getElementById("ds");
var r1 = document.createElement("div");
r1.innerHTML = n1.textContent;
document.body.appendChild(r1);
n1.parentElement.removeChild(n1);
};
var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
if (raf)
raf(function () {
window.setTimeout(dfr, 0);
});
else
window.addEventListener("load", dfr);
The CSS is located within a <noscript> block as a fall back.
The JS then moves this CSS into a div it creates the second the page has loaded.

Site breaking down 2 seconds during load

Hi I have a wordpress websitse. When I try to visit that site it breaks down full layout for minimum 2 seconds. I can't understand why this is happening. I tried to use Javascript to footer plugin.
Please suggest me what happened here. And what can I do in this situation.
I can see you're using Divi theme in your wordpress site. I believe the above problem is due to loading css at the end of body.
When I inspect your site, I am able to see main css file such as Divi/style.css (Parent theme style) is loading at the end of body. Hence I came to this conclusion. Try moving your css to head that would solve your problem.
Incase you're concern about site speed try moving css one by one to head.
This is because you are writing the link rel="stylesheet" which is poor poor practice. Add it in head and your problems will be solved.
Do not write your main stylesheet in body tag, if you do not want that effect.
Further reading
https://stackoverflow.com/a/16844668/17447
load external css file in body tag

Dynamically and asynchronously loading CSS (by setting the "href" attribute in Javascript)

On our site we load stylesheets dynamically based on whether the display is retina or not. Right now, we are using document.write for each <link href="stylesheet.css"> we insert in the page, with different css files if the display is retina.
However, this hurts performance because it causes the css files to load synchronously, as the browser has no way of parsing the javascript to load the next file before the previous one is finished. I believe we can reduce page load time if we take advantage of modern browsers' capability to look ahead and fetch resources asynchronously - in another words, if we load the CSS files in parallel instead.
My current solution is to create a <link id="link-tag-id" href=""> tag for every stylesheet to be loaded, immediately followed by a script which determines the retina status, then fills in the quotations with the appropriate file, along the lines of:
document.getElementById("link-tag-id").setAttribute("href", "retina-stylesheet.css")
This seems to work fine, and when I examine the network waterfalls in Chrome developer tools, as well as on WebPageTest.org (running Chrome, Firefox, and IE), the stylesheets indeed load in parallel. However, it seems a little hacky. I was wondering if there are any dangers to creating a <link> tag with an empty href attribute, and if so, what are they?
On a broader note, are there any other recommendations on how to load CSS dynamically and asynchronously?
Thanks for your help!
EDIT: I just discovered this works too:
document.getElementById("link-tag-id").href = "retina-stylesheet.css"
You could use media queries inside your stylesheet to determine if the display is a retina display, then load in the required CSS.
http://css-tricks.com/snippets/css/retina-display-media-query/
http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/

In mobile devices, which is faster: including an extra CSS file OR creating a style element in JavaScript?

If I have an HTML page that includes some JavaScript, for example:
<script type="text/javascript" src="http://example.com/code.js" async></script>
And I want to add some CSS, which of the following 2 options is faster, performance-wise?
Option 1
(More "Network Heavy")
Including the CSS in a separate inline tag, for example:
<link rel="stylesheet" type="text/css" href="http://www.example.com/style.css">
OR
Option 2
(More "JavaScript Execution Heavy", since it requires DOM manipulation) injecting the CSS into the DOM from inside the included JavaScript file, for example (taken from: https://stackoverflow.com/a/707580/1785003]1):
var css = document.createElement("style");
var css = "text/css";
css.innerHTML = "strong { color: red }";
document.body.appendChild(css);
The 2nd option removes a network request from the page, but requires DOM manipulation, which might be costly in Mobile Device browsers.
So which is better?
I do not believe there is much of a difference between a mobile device and regular browser in the way they load and cache pages so I would treat them the same.
Having CSS in your JavaScript is going to be a maintenance nightmare. Probably not worth any tiny (if any) optimisation gain. As Pekka pointed out after initial load it will cached.
You will be better off targeting other performance optimisations first. Like Minify CSS and javascripts, CSS sprites etc . Use a tool such as yslow to help show where performance optimisations can be made.
Also most browsers can make at least 4 concurrent request to the same host so that the CSS and Javascript , HTML can all be downloaded at the same time. See here
Answering from Performance POV:
Using CSS is a better option.
Reason
Performance is not just measured in network bandwidth consumption. JS blocks the rendering of the page till they're completely downloaded.
(Note: html 5 now suports
<script type="text/javascript" src="http://example.com/code.js" async></script>
which frees loading of rest of your markup in parallel.)
Once css is fetched for first time, then it is neither downloaded nor executed (vs javascript). This is delight for returning users.
Solution
Use the external css and keep it at the top of your semantics (in <head> section, preferably).
Use external js and keep it at the bottom of the page (near the </body> tag)
Background:
Have worked with Yahoo! and adhered to their Best Frontend practices.
Put Stylesheets at the Top
Put Scripts at the Bottom
The CSS file will definently render faster, once it's downloaded and processed, since browser are optimised for this. Applying via JS means that you need to wait for the document to load, then seek elements, apply styling, and then allow the browser to do its magic.
In my experience, adding a CSS file for anything more than dynamic behavior by far outweights any "speed" decrease due to maintainability (how easy it is to change something) and because you can actually restyle your page without editing the code part, which can break things (if for instance you change the JS generating the styles and forget a quote, you break the page, and lose all JS for that page).
The only situation where styling via JS is ok for non-dynamic behavior, is when its a few lines all in all, and even then I'm cautious.

Font-face flickering when new css files are dynamically loaded

I am using the Google Webfont Loader to get my webfonts loaded with a callback and it is working fine.
Although, when a couple of components: Google +1 button, Twitter Search Widget and the Add This button is loaded, they add a new stylesheet to the DOM and makes the browser render the site again. This is causing the font-face to disappear and then show for each new stylesheet added to the dom.
I could hide the font entirely until the components are loaded but they tend to be pretty slow so that would leave me with a pretty bad user experience. About 1 sec of a headline-less site.
Andy tips on how to force font-face to not redraw or how to block dynamically loaded CSS from within Google, Twitter and FBs embed scripts?
Update: Demo here http://kristoferforsell.com/dev/fontexample/
This is currently an inherent issue with browsers and the #font-face property. The blink occurs when the font is loaded and the page updates to reflect the font. If you wish to remove the "blink" entirely, the only sure fire way is to include the font as a data URI in the style sheet. Of course, using the standard "safe" fonts will also remove the blink.
Data URIs allow you to actually embed the code for the font in the stylesheet so there's no blink when the page refreshes to show the desired font. Using data URIs, will obviously increase the file size (kb) of any style sheet.
An online converter to get base64 code can be found here
Usage for #font-face would be like so.....
#font-face {
font-family: "My Font";
src: url("data:font/opentype;base64,[ the base64 code here ]");
}
Not sure if it would fix your issue but you could use css to set the visibility of the elements to hidden until the font is loaded. Google's API provides wf-loading and wf-active classes which are added to the body to address this issue.
I always set up a separate stylesheet just for the #font-face rule, and within that put in the following rules, where replace is the class of the element that's being replaced, for you that would just be the p tag.
.wf-loading .replace { visibility: hidden;}
Yours would be
.wf-loading p { visibility: hidden;}
Then as soon as the webfont is loaded, JS puts the wf-active class on the body, and your text shows up. Let me know how that goes and if you have any issues then just drop me a line. It might also be worth doing some searching for "flash of unstyled content" or "flash of unstyled text" as this is a well known and well documented bug.
I can suggest a simple and dirty trick I have used myself to solve issues like this. If you implement this, from the user's side the effect will be that the entire page will load at once (with the correct Web Fonts), but after a delay. Once loaded, nothing will flicker or change.
Wrap your entire page contents in a div and set its visibility to hidden. Then use js to turn on the visibility once the whole page (stylesheets and all) is loaded.
Here's the code:
<head>
<script>
function show()
{document.getElementById('wrapper').style.visibility='visible';}
</script>
</head>
<body onload="show()">
<div id="wrapper">
...your entire page contents...
</div>
</body>
The onload ensures that the visibility is switched on only after the entire body has loaded. Although I haven't used Web Fonts, I use this trick to fade in the entire contents of this website with no changing or updating afterwards. But yes, there will be a delay before the entire page comes into view.
EDIT: I added Google Web Fonts to the site I linked. Still works fine. No font-face flickering.
This is a shot in the dark, as I've not tested it:
Could you create another html page with only those social networking buttons, and then load that into an iframe? Then only set the src to the iframe once the document is fully loaded, so it doesn't hold anything up.
In html:
<iframe id="socialMedia"></iframe>
In script:
$(document).ready(function() {
$('#socialMedia').src = "http://mysite.com/mysocialmediastrip.html";
});
Where mysocialmediastrip.html contains all the social media buttons. Setting the src will cause that iframe to reload and pull in that content, but IIRC, the rest of the page will be left alone -- all of the button rendering will have been done in mysocialmediastrip.html, not in your main page.
I totally understand what you are saying about the delay process, waiting while window loads before you actually show your goods. Abhranil provided a good solution but you can take his solution further. You can use jQuery's ajax to load your specific page content that's using the special font type. Why? because ajax comes with a special function called beforeSend(). Within the beforeSend function(), you can load a very cool gift animation that will display on your screen, before your main content is ready to viewed.
Use that moment to show some creativity towards your audience, before the main event!
The best and most simple answer is adding font-display: block when specifying a font face
#font-face {
font-display: block; /* Fix flickering */
}
You should also preload the font in the html file
<head>
<link rel="preload" as="font" href="/path_to_your_font.ttf">
<-- repeat for all typeface -->
</head>

Categories

Resources