Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

HTTP2 Push Header - Feature Suggestion #49

Open
2aces opened this Issue Jul 20, 2016 · 83 comments

Comments

Projects
None yet
10 participants

2aces commented Jul 20, 2016 edited

Hey, @futtta . Celso Bessa, AO pt-br translator here.

As you know, HTTP2 push is a big deal in optimization now. We are getting great results in some of our projects with it and I think it would be great if AO included a mechanism to use those headers.

In some test setups we filtered AO final JS/CSS srcs and created our own headers using PHP/WP send headers ( https://codex.wordpress.org/Plugin_API/Action_Reference/send_headers ). this is not hard for us, but it might be not easy for an non technical user.

In other setups we used AO alongside http2 server push plugin by @daveros ), which is great, but it sends headers for all files in the original wp_enqueue queue but not for AO aggregated files (my guess is it uses a hook triggered before AO).

Looking this 2 cases, seems to me that having this on AO would help a lot of you user base.

What do you think? I won't be able to code anything for the next 4 weeks, but if you think it's a good feature, I can work on this in august.

Owner

futtta commented Jul 21, 2016

absolutely! :-)

but does this work when using page cache plugin and when AO is set to deliver static files? because in that case you might not have any PHP to start with?

@futtta futtta added the enhancement label Jul 21, 2016

2aces commented Jul 21, 2016

All tests were done on WPengine (which uses a custom varnish implementation, I think) with and without Cloudflare. I guess their cache keeps the headers sent by the original PHP page in the static version.

I will check on other hosts and let you know the results ASAP.

Owner

futtta commented Jul 21, 2016

So I read up on the topic a bit :-) and found this interesting article on smashing mag. about preloading, which focuses primarily on the HTML-based preloading (but also mentions the HTTP header-approach).

I think adding the preload both as HTTP resp. header and in the HTML (link rel=preload) would ensure that even in a fully static setup (where headers are not cached) the resources would be loaded over the existing HTTP/2 connection (@daveros does the same, actually)?

2aces commented Jul 21, 2016 edited

TL;DR

  • That's the approach we use on our production sites and apps. It should work with AO.
  • check both specifications drafts for preload and other resource hints and Ilya Grigorik notes on the subject.

The Long Version (food for thought)

So far, we use a custom plugin to each site, aggregating all functions, AO filters and techniques for optimization, including different resources hints ( https://www.w3.org/TR/resource-hints/ ) for different resources to ensure maximum browser support, depending on the resource importance, origin, position and how sure we are we will use a given resource:

    <link rel="preconnect" href="https://api.tiles.mapbox.com">
    <link rel="dns-prefetch" href="https://api.tiles.mapbox.com">
    <link rel="preload" as="script" crossorigin href="https://api.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js">
    <link rel="preconnect" href="https://api.mapbox.com/">
    <link rel="dns-prefetch" href="https://api.mapbox.com/">
    <link rel="preload" as="style" href="https://mydomain.com/path-to-ao-cache/ao-aggregated-style.css">
  • Line 1: we know we need to connect to that domain, but not exactly which resource. We use preconnect to suggest browsers which support it to initiate connection.
  • Line 2: this hint has a wider browser support, we use as fallback for browsers that don't support the previous hint to make the initial DNS lookup. In our tests, browsers supporting preconnect ignore this one if the connection on line 1 was made (all resource hints are suggestions... er, hints... and UA decides if it will process it) .
  • Line 3: We know exactly which resource we want and it's really important. Let's preload it in browsers that support it. Note that we need both the crossorigin andas parameters if said resource is external.
  • Lines 4 and 5: act as fallback for browsers not supporting preload, same way like lines 1 and 2.
  • Line 6: we know we will need this über important resource, lazy-loaded by AO. So, let's fetch it.

Since last week, we're shipping our plugins with our send header functions just with preload for the most important resources. That's what "triggered" our suggestion, because we thought it would be great for other AO users. :-)

I guess AO would work great with just preload on headers and inline, but if you want to have wider browser support, use preconnect and dns-prefetch as well. This should be filterable/optional because it will work great most of time, but sometimes it won't, depending on the aggregated file size, original CSS rules, dom complexity, etc

Owner

futtta commented Jul 21, 2016

great work, interesting stuff! looking forward to your contributions!!

Contributor

zytzagoo commented Aug 11, 2016

Some interesting details here: https://blog.yoav.ws/being_pushy/

2aces commented Aug 11, 2016

@zytzagoo interesting article indeed

If you guys need anything, just send me a Short message and I can Look into
it :-) ;-)

On Friday, 12 August 2016, 2ACES notifications@github.com wrote:

@zytzagoo https://github.com/zytzagoo interesting article indeed


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
#49 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/ARjhk8fr6H0knFE1nvjsvAxHR3qruc04ks5qe5cHgaJpZM4JRNhx
.

Best Regards

Ylia Callan

WEB SWIFT SEO
Tips - Tools - Techniques

https://webswiftseo.com

trajano commented Aug 19, 2016 edited

Can

$content = apply_filters( 'autoptimize_html_after_minify', $content );
be changed to pass in the URL for the cached + minified CSS and JS? That way we can do

function http2_server_push($content, $cached_js, $cached_css) {
  header(
    sprintf(
      'Link: <%s>; rel=preload; as=%s',
         $cached_js, 'script'
    )
  )
  header(
    sprintf(
      'Link: <%s>; rel=preload; as=%s',
         $cached_css, 'style'
    )
  )
}
add_filter('autoptimize_html_after_minify', 'http2_server_push')
Owner

futtta commented Aug 19, 2016

well, I think at the very least we should hook into wordpress' send_headers action hook to avoid sending headers out of order.

trajano commented Aug 19, 2016 edited

Anyway the workaround I have for now is

function http2_server_push($content) {
  $header = "Link: ";
  if (preg_match('#="([^"]+/js/autoptimize_[0-9a-f]+\.js)"#', $content, $matches)) {
    $header .= sprintf(
        '<%s>; rel=preload; as=%s,',
           $matches[1], 'script'
      );
  }
  if (preg_match('#="([^"]+/css/autoptimize_[0-9a-f]+\.css)"#', $content, $matches)) {
    $header .=
      sprintf(
        '<%s>; rel=preload; as=%s',
           $matches[1], 'style'
      );
  }
  header($header);
  return $content;
}
add_filter('autoptimize_html_after_minify', 'http2_server_push');

Seems to work a bit on my blog https://www.trajano.net/. I see the JS, CSS being loaded as soon as possible when I check the network graph.

Owner

futtta commented Aug 20, 2016

Nice! It does work; your AO JS is linked at the end of the HTML, with defer attribute, but it is indeed loaded immediately as per this webpagetest.org test which also shows that the initial request has this as header;

link: <https://www.trajano.net/wp-content/cache/autoptimize/js/autoptimize_7f1fb7f2c06f6c4218428fe4c1904176.js>; rel=preload; as=script,<https://www.trajano.net/wp-content/cache/autoptimize/css/autoptimize_dc58df74105fec34d124e8ddef6f0210.css>; rel=preload; as=style

the only thing which I can't deduct from the waterfall chart is that the preloaded CSS/ JS isn't render-blocking (it shouldn't as per the specs, obviously).

If I were you I would install a page cache plugin to minimize my TTFB, would be interesting to see if such a plugin also caches headers?

trajano commented Aug 20, 2016

I would agree with the page cache. I just never got around to doing it, I've tried a few before (like years ago) but they had some issues on a very limited memory machine and running on Oracle Linux with SELinux on full blast. It may be better now, but I never invested time on it.

However for one thing I don't like having to wait on the cache, I would rather it change as I change things. Since my blog is more for play around rather than a heavily utilized site.

trajano commented Aug 20, 2016

What I would like to know is if it were at all possible to send the headers ASAP then the content because it looks like it processes the whole page first. But then a cache would likely help there.

Owner

futtta commented Aug 21, 2016

it simply has to process the page first, as:

  • headers are sent as part of the actual HTTP response
  • autoptimize needs the full page to extract & optimize the CSS/JS and you need AO to extract the to-be-preloaded URL's

so yeah, I would go the page cache route :-)

trajano commented Aug 21, 2016 edited

Tried using WP Super Cache (had it's share of issues with permissions and what not) but I got it working in the end. I lose the headers now :(

Content is faster though.

https://www.webpagetest.org/result/160821_V0_F2D/2/performance_optimization/#first_byte_time

Owner

futtta commented Aug 21, 2016

I guess (hope) there must be page caching plugins that also cache headers ...

trajano commented Aug 21, 2016 edited

Here's a slightly better one that I am using, it will scan through and preload all JS, CSS PNG and JPGs that are found in the content. I kind of want to remove the second regexp, but got lazy :)


                        $header = "Link: ";
                        $regexp = '#(src|href)="([^"]+\.(js|css|png|jpg)(\?[^"]+)?)"#';
                        if (preg_match_all($regexp, $uncompressed_file_data, $matches, PREG_SET_ORDER)) {
                                foreach ($matches as $match) {
                                        $file = $match[2];
                                        $type = $match[3];
                                        if ($type === 'js') {
                                                $type = 'script';
                                        } else if ($type === 'css') {
                                                $type = 'style';
                                        } else {
                                                $type = 'image';
                                        }
                                        $header .= sprintf('<%s>; rel=preload; as=%s,', $file, $type);
                                }
                        }
                        $regexp = str_replace('"', "'", $regexp);
                        if (preg_match_all($regexp, $uncompressed_file_data, $matches, PREG_SET_ORDER)) {
                                foreach ($matches as $match) {
                                        $file = $match[2];
                                        $type = $match[3];
                                        if ($type === 'js') {
                                                $type = 'script';
                                        } else if ($type === 'css') {
                                                $type = 'style';
                                        } else {
                                                $type = 'image';
                                        }
                                        $header .= sprintf('<%s>; rel=preload; as=%s,', $file, $type);
                                }
                        }
                        header(rtrim($header, ","));

@2aces

There are two preloads around and it can cause confusion.

The W3 link you linked is not a push preload. It is just an instruction to the browser to fetch a resource with highest priority (and not execute it or use a code onload).

This can be done even if there is no HTTP2.

The other preload is of course pushing assets to the browser.

trajano commented Aug 22, 2016

For server push you need two things: the Link header and a server such as nghttp2 that can parse the Link header and start sending. I haven't gotten it to work with nginx yet.

Some thoughts:

Push optimisation is the best when the critical css is pushed and the html doesn't have any inline/critical css. It's a separate file.

Pull preload for the full css file will be as good as the push css.

It's pushing the critical css which can make the difference.

As Ilya Grigorik says:

n fact, if you have ever inlined a resource (CSS, JS, or an image), you've been "simulating" server push: an inlined resource is "pushed" as part of the parent document. The only difference is that HTTP 2.0 makes this pattern more efficient and far more powerful! ... HTTP 2.0 server push obsoletes inlining.

https://www.igvita.com/2013/06/12/innovating-with-http-2.0-server-push/

So if it's something to be pushed ... it's the critical css, not the full css.

In other words, the best optimization is:

  • critical css is not inlined and pushed as an external css.
  • the html has a render blocking link declaration for the critical css.
  • the full css is fetched via a pull preload, not pushed.

2aces commented Sep 6, 2016

Just to give some sanity check, we are not talking about only HTTP2 push header anymore, right? If so, maybe we should change the Issue title and description.

2aces commented Sep 6, 2016 edited

  1. we gotta evaluate which resources to support;
  2. we gotta evaluate which methods will be available (link element, http2 push);
  3. decide if we use WordPress 4.6 class or write our own;
  4. which ones will be available on settings and which ones only by filters;

What is sure is that every setup will have different demands and outcomes. I mean:

  • 1 page sites VS sites with lot of pages VS sites with something in between have different demands?
  • Theme templates which are almost the same VS too diferent post type and archives templates.

Specifically about preload AND HTTP2 push, we gotta be careful as @zytzagoo pointed out, it may result in overhead for subsequent page visits . In my specific test setups on WPEngine with sites with small diferences, it was worth anyway.

Build on what @vijayaraghavanramanan listed as the best optimization:

  • critical css is not inlined and pushed as an external css (1)
  • the html has a render blocking link declaration for the critical css (2)(3)
  • the full css is fetched via a pull preload, not pushed (4).
    - the full css is inserted on DOM dynamically as is done today when using inline CSS(5)
  • (1) optionally, via filter, keeping backwards compatibility and non-advanced users sanity).
  • (2) optionally as effect of the previous one.
  • (3) why not pushing it, specially when using an CDN, aiming to avoid blocking for long times while waiting the DNS lookup and download. After all this is the critical one and should be parsed and applied ASAP.
  • (4) why not an option of doing both, via filter?
  • (5) some browsers don't support preload and some servers won't have HTTP2 headers push support, and even they do, it may take some time to download the CSS, so, loading dynamically will keep users happy any way.

PS: @trajano your code looks efficient for this, as soon as I am able, I will test it.

2aces commented Sep 6, 2016

About using WordPress class: it doesn't support preload right now. I think the best course of action would be expanding it for preload and HTTP2 push headers and if works good, we propose it to merge it on core.

@2aces,

Correct.

Only Chrome/Opera support preload in stable and Firefox is building it but not in Nightly yet. My points were incomplete.

So I should say my points should read:

  • critical css is not inlined and pushed as an external css.
  • the html has a render blocking link declaration for the critical css.
  • the full css is fetched via a pull preload, not pushed and applied via "onload" in the link rel declaration.
  • for browsers which do not support preload, polyfill it with Autoptimize's existing js.
  • for these browsers also use a sessionstorage variable to optimize on second load, i.e, load the full css immediately in the head on repeat website view.

I mentioned not pushing the full css as one should push as less as possible. So html and critical css can load fast if that's the case.

2aces commented Sep 7, 2016

@vijayaraghavanramanan :

"for browsers which do not support preload, polyfill it with Autoptimize's existing js."
My understanding of preload draft specification and for all tests I conducted is that pushing the CSS using http2 push doesn't mean it is inserted in the DOM and parsed, it is only downloaded. Therefore, we need AO javascript even when the browser and server supports pushing headers.

"for these browsers also use a sessionstorage variable to optimize on second load, i.e, load the full css immediately in the head on repeat website view."
Can you elaborate?

vijayaraghavanramanan commented Sep 7, 2016 edited

@2aces

Right. It's just downloaded. But it allows what you can do onload. So that's why I said onload in point 3 in my previous comment.

So you can declare it like this:

<link rel="preload" href="http://www.example.com/wp-content/cache/autoptimize/css/autoptimize-hash.css" as="style" onload="preloadFinished(this)">

and before it define a function in javascript

<script>
function preloadFinished( el ) {

...

}
</script>

or pass href instead of this

About sessionstorage, what I meant was that once a visitor visits a site the css file is already in the cache. So for repeat views, you can do better than loading css in the footer. The browser now doesn't need to fetch the css from the server as it is in the cache.

So in the footer, add this line in javascript:

sessionStorage.fullaocssloaded = "true";

And in the header,

<script>
if (! relpreloadsupport) {
  if (sessionStorage.fullaocssloaded ) {
     //javascript to insert the full css immediately. 
 }
}
</script>

What the above code does is that it checks if there's a sessionStorage variable. If true, it means almost certainly that the css is in the cache. So why not load it in the head.

It's slightly more complicated as some browsers do not allow sessionStorage in incognito mode.

This is the full javascript code. It use requestAnimationFrame, but you can use Autoptimize's lCSS instead.

The code is a collection of various snippets at various points in the HTML, not to be used next to each other.

function preloadFinished(node) {
    var res = document.createElement("link");
    res.rel = "stylesheet";
    res.href = node.href;
    node.parentNode.insertBefore( res, node.nextSibling );
}

var linkSupportsPreload = function() {
    try {
        return document.createElement("link").relList.supports("preload");
    } catch (e) {
        return false;
    }
};

var sessionStorageAvailable = function() {
    var mod = 'modernizr';
    try {
        sessionStorage.setItem(mod, mod);
        sessionStorage.removeItem(mod);
        return true;
    } catch (e) {
        return false;
    }
};

var cb = function() {
    var links = document.getElementsByTagName("link");
    for (var i = 0; i < links.length; i++ ) {
        var link = links[i];
        if( link.rel === "preload" && link.getAttribute( "as" ) === "style" ) {
            preloadFinished(link);
        }
    }
}

if( !linkSupportsPreload() ) {
    if( (sessionStorageAvailable() && sessionStorage.fullcssloaded) || !sessionStorageAvailable() ) {
        cb();
    }
}

var rAF = (function() {
    return window.requestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || window.webkitRequestAnimationFrame || function( callback ) {
        window.setTimeout(callback, 1000 / 60);
    }
})();

if ( !linkSupportsPreload() ) {
    if( sessionStorageAvailable() && !sessionStorage.fullcssloaded ) {
        setTimeout(function() {
            rAF(cb);
            sessionStorage.fullcssloaded = "true";
        });
    }
}

Btw in select cases, it makes sense to just have the full css pushed and block render with the full css and not have critical/above the fold css at all.

It won't have the problems of speed as the css arrives at the same time as the initial HTML, so rendering is fast as the usual "inline and defer"

But that's in the case where the full css is not a big file. If it's big, it makes sense to push the critical css file only.

vijayaraghavanramanan commented Sep 27, 2016 edited

I have a slightly improved optimization method below. The simplest solution is of course is to push the full css. But this is not optimal as its size can be greater than 14KB. Some Wordpress bundled themes have things such as Genericons which are huge and its not optimal to push them.

My improvement to the previous comments is that for second loads, you don't need critical css. The server might still push it for second loads (but some are thinking of improvements to cancel it from the client side) and it's still better to not use it and thus avoid repaints.

  • Push critical.min.css and insert it synchronously via javascript depending upon whether the page has a sessionstorage variable. (My earlier comment said insert it via link). If the page doesn't have sessionstorage variable set to true, insert it synchronously, else don't use critical.min.css. Effectively first load uses critical.min.css but second load doesn't).
  • Fetch the full style.min.css via pull preload (not push) and apply it onload if the page doesn't have sessionstorage variable. If the page has sessionstorage variable set to true, don't pull preload and instead insert style.min.css via javascript synchronously.
  • For browsers not supporting pull preload, polyfill (the second point).

(Browsers which don't support HTTP2 push see very old behaviour, don't enjoy "inline and defer". Minor sacrifice since most modern browsers do support HTTP2 push).

Owner

futtta commented Sep 27, 2016

My 2c:

  • as HTTP/2 support doesn't only depend on client but also server and as I want AO support to be as broad as possible (and as I like clean and simple solutions), I would by default (so this could be different behind a filter, but that filter would for now default to false) keep inline CSS inline, also for 2nd loads, the overhead is minimal and this is never render-blocking (so only disadvantage is slightly bigger HTML payload).
  • the pull preload solution is fancy, but rather complex esp. with that polyfilling going on (e.g. I don't want to depend on modernizr in AO)
  • push is the future

Hi Frank,

Yeah, It's just catching up and would imagine only few percent of server fully supporting it. This is because in addition to supporting push, they also need to be HTTPS. Push can work without HTTPS but browsers have implemented it so that it can work only in HTTPS. So inlining critical css as AO default makes sense.

About my code, I took it from Modernizr but doesn't depend on it. So alternatively one can use this from Mozilla's site:

function storageAvailable(type) {
    try {
        var storage = window[type],
            x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return false;
    }
}

if (storageAvailable('localStorage')) {
    // Yippee! We can use localStorage awesomeness
}
else {
    // Too bad, no localStorage for us
}

with sessionStorage instead of localStorage.

trajano commented Jan 23, 2017 edited

I had a recent finding with HTTP2 Server Push, but it may just be a Chome bug/limitation. https://trajano.net/2017/01/double-downloads-with-http2-server-push/ if you preload and the resource is not dynamically added using scripts in Chrome you will get a double download.

However, given that we can probably do an optimization where the CSS is added to the DOM by the script and asynchronously loaded. With HTTP/2 Server Push the CSS can be preloaded in the background while the initial DOM is being processed and then bound later by the script.

Owner

futtta commented Jan 25, 2017

weird that you got

The resource … was preloaded using link preload

while you were not preloading via a link but via the HTTP response header? or were you doing both?

trajano commented Jan 25, 2017

Either one will yield the same problem. Doing in Link header will just download a bit more data sooner I presume because of Server Side push. Again I think it could be a Chrome implementation issue, because I do not see anything in the spec that states that it needs to be loaded via script. But then again it could be worded differently.

I have seen those sort of Chrome warnings but it's usually because something is not done right.

This is a good page and I don't get any warning here on Chrome:

https://www.filamentgroup.com/lab/modernizing-delivery.html

@trajano
Very interesting approach, I want to use it.
Would you share the most recent version of your code?

trajano commented Feb 11, 2017

@vijayaraghavanramanan i think it a proper way to validate is to find out whether the a resource was sent via H2 AND downloaded as part of the webpage request either via Link header or some other way. By doing the H2PushResource it may tell Apache to explicitly send the resource over the wire but they could just be sent without being attached and redownloaded again.

trajano commented Feb 12, 2017

I don't have a updated to the latest version of Cache-Enabler, I did a diff and the key functions are below for wp-content/plugins/cache-enabler/inc/cache_enabler_disk.class.php

private static function endsWith($haystack, $needle)
{
            $length = strlen($needle);
            return (substr($haystack, -$length) === $needle);
}
private static function _link_header($uncompressed_file_data) {
        $header = "";
                $regexp = "#'((https?:)//[^']+/[^/']+\.js(\?[^']+)?)'#";
                 if (preg_match_all($regexp, $uncompressed_file_data, $matches, PREG_SET_ORDER)) {
                         foreach ($matches as $match) {
                                 $file = $match[1];
-
                                 $type = 'script';
                                 $header .= sprintf('<%s>; rel=preload; as=%s,', $file, $type);
                         }
                 }
                 $regexp = str_replace("'", '"', $regexp);
                 if (preg_match_all($regexp, $uncompressed_file_data, $matches, PREG_SET_ORDER)) {
                         foreach ($matches as $match) {
                                 $file = $match[1];
                                if (self::endsWith($file, '/html5.js')) {
                                        continue;
                                }
                                 $type = 'script';
                                 $header .= sprintf('<%s>; rel=preload; as=%s,', $file, $type);
                         }
                 }
                $regexp = '#(src|href)="([^"]+\.(css|png|jpg)(\?[^"]+)?)"#';
                 if (preg_match_all($regexp, $uncompressed_file_data, $matches, PREG_SET_ORDER)) {
                         foreach ($matches as $match) {
                                 $file = $match[2];
                                 $type = $match[3];
                                 if ($type === 'css') {
                                         $type = 'style';
                                 } else {
                                         $type = 'image';
                                 }
                                 $header .= sprintf('<%s>; rel=preload; as=%s,', $file, $type);
                         }
                 }
                 $regexp = str_replace('"', "'", $regexp);
                 if (preg_match_all($regexp, $uncompressed_file_data, $matches, PREG_SET_ORDER)) {
                         foreach ($matches as $match) {
                                 $file = $match[2];
                                 $type = $match[3];
                                 if ($type === 'css') {
                                         $type = 'style';
                                 } else {
                                         $type = 'image';
                                 }
                                 $header .= sprintf('<%s>; rel=preload; as=%s,', $file, $type);
                         }
                 }
                 return rtrim($header, ",");
}
Owner

futtta commented Apr 4, 2017

So open question; is HTTP2-pushing (almost) all resources (js, css, images) a good idea? Or should one rather push those resources that are needed for the initial page rendering?

trajano commented Apr 4, 2017

If you can somehow push those that are part of the theme (i.e. scripts, CSS) that would be better. However, they will only work when the data is loaded via script rather than part of the source. https://trajano.net/2017/01/double-downloads-with-http2-server-push/

If HTTP/2 is going to be enabled somehow it should defer the scripts and CSS

I am not sure if that double downloads issue is fixed on the current versions on Chrome though.

trajano commented Apr 4, 2017

Another approach I can think of is to NOT do anything automatically to determine what should be pushed. Instead let the theme or blog developer do it themselves by having <link rel="preload" ... tags in their content. These tags will then be parsed and stripped off so it will be sent via the HTTP Headers instead. The purpose of having them on HTTP Headers rather than the content is for HTTP2 Server Push compatible servers it should start sending the data ASAP before the client had requested it.

Owner

futtta commented Apr 4, 2017

How is support for HTTP/2 push now, which servers support that out of the box?

Owner

futtta commented Apr 4, 2017

trajano commented Apr 4, 2017

Not anymore, I found that it didn't work too well in Chrome. It was actually causing double downloads.

trajano commented Apr 4, 2017

The main problem is Chrome will only "link" the content if it was built from a script rather than the HTML. So <img src=... /> will double download but setting .src via JavaScript will not.

trajano commented Apr 4, 2017

I still preload a few things on my main portfolio https://trajano.net/ however, since they're all remote resources (i.e. google fonts etc) it won't be server push. Only those that are authorative can be server push.

Owner

futtta commented Apr 4, 2017

re. double downloads; sounds vaguely related to filamentgroup/loadCSS#110

trajano commented Apr 4, 2017

Many issues... it may not be fixed though unless the spec has made it explicit that it should also be for non-scripted resources. So far only script injected resources will not be double downloaded.

https://bugs.chromium.org/p/chromium/issues/detail?id=655698
ampproject/amphtml#7076

Owner

futtta commented Apr 4, 2017

more in:
https://bugs.chromium.org/p/chromium/issues/detail?id=655698
w3c/preload#80

But these focus on a correct as= attrib. missing, which was not the case for you was it @trajano ?

trajano commented Apr 4, 2017

I think it is more that it is dismissed already regardless I found that we shouldn't try to do guess what needs to be sent automatically and instead rely on the actual theme developer (which is why I stated use the resulting data. Stripping it off and sending it as part of the header would have some benefit HTTP2 will package the header more efficiently.

Owner

futtta commented Apr 4, 2017

Well, for a site using AO (which is our context after all) I think HTTP2-pushing the autoptimized CSS & JS (and jquery, if excluded) could make sense actually :-)

trajano commented Apr 4, 2017

Owner

futtta commented Apr 4, 2017

You cannot push jquery unless you defer loading jquery.

that part I didn't understand. is that the bug/ limitation you stumbled upon, or just as the spec intented?

However the interim of doing the link parsing will help.

what do you mean by that? harvesting link's in the header looking for preload and pushing those? doesn't really apply in AO's context, as AO aggregates all linked CSS replacing it with between 1 and 3 (generally, depends on different media-attribs in the original links) files.

configure the server automatically

must be getting tired, but I don't understand that part either, would you care to elaborate?

trajano commented Apr 4, 2017

Owner

futtta commented Apr 5, 2017

Indeed, but that's for in-HTML link-preload, question is if this would also (still) happen when (only) doing HTTP/2 push (i.e. in HTTP response header).

FYI (and just because I haven't seen it being mentioned) - the Cloudflare plugin supports HTTP/2 push (activated using a wp-config directive) and adds headers and <link rel="preload" as="script|style"> entries in the <head> - of course it doesn't do any good with autoptimize enabled, but at least gleaning at the source might be of interest.. 🙂

2aces commented Apr 26, 2017

Just pinging here to 1 - apologize for not being active in the discussion/development because of health and other issues 2- fantastic collaboration in this post/feature, guys.

Owner

futtta commented Apr 26, 2017

@2aces: get better soon!

@PatTheMav : wonder if combining HTTP/2 push (i.e. link preload in HTTP response headers) and link rel=preload in HTML <head> would not result in unwanted behavior? Have you been able to test this?

PatTheMav commented Apr 26, 2017 edited

@futtta - not yet, as I'm primarily using Safari, so I'd have to check this in my Windows VM on Edge.. 😉

But their docs make it seem like it's a "enable & forget" feature:

https://support.cloudflare.com/hc/en-us/articles/115002816808-How-do-I-enable-HTTP-2-Server-Push-in-WordPress

The source code itself mentions the following about adding the <link> elements:

Render "resource hints" in the section of the page. These encourage preload/prefetch behavior when HTTP/2 support is lacking.

Also it's just adding the headers using PHP's header function after adding itself as a filter for the script_loader_src and style_loader_src events. In addition it's mentioning an 8kb header size limit for Cloudflare (and a 4kb header size limit for fastcgi) so it limits the size of the header field to 3072 bytes (including CLRFs).

I'm not too versed with Wordpress' innards, so I don't know if there is a more elegant way to pull this off, but it seems workable.

Edit: Of course there is the elephant-in-the-room question about jQuery and many themes' reliance on jQuery being fully loaded in the head.

Owner

futtta commented Apr 28, 2017 edited

@PatTheMav I think we would indeed need to HTTP/2-push jquery.js, yes. we'll also have to (re-)consider deferring JS. if HTTP/2-pushed, the JS would not render-blocking (although the execution might be, cfr. "async"-flag which makes downloading not render-blocking but the actual execution is) so deferring (which delays JS execution until very late in the process) might not be optimal.

options options options ... ;-)

trajano commented Apr 28, 2017

Owner

futtta commented Apr 28, 2017 edited

i never defer jquery.js, in ao's default config it's even excluded from optimization. the point i was trying to make is that we might want to http/2-push jquery.js though :)

PatTheMav commented Apr 28, 2017 edited

@trajano - I'd say it's common practice to exclude jQuery from any deferred loading (and is more or less the default in AO). But @futtta is right that HTTP/2 push might make deferring itself (or placing in the footer) obsolete.

Personally I have no idea how the JS execution stack works in that case though, especially in conjunction with the event loop. There's a reason why some jS still "wants" to be loaded and parsed in the <head>, also some JS makes quite "optimistic" assumptions about when and how it's being loaded.

Owner

futtta commented May 31, 2017

regarding cloudflare; relevant code is here

regarding article @zytzagoo shared; interesting they make a distiinction between push and preload, as (based on what I read) webservers also use the preload http response header to determine what to push?

Owner

futtta commented May 31, 2017

although I'm mainly working on stablizing AO 2.2 (hope some of you have it running, need to be more or less confident it's OK before releasing), this code snippet (a proof of concept, nothing more) pushes the AO'ed files and jquery.js;

add_filter('autoptimize_filter_cache_getname','pushAOFiles');
function pushAOFiles($in) {
  $pushType = substr($in,strrpos($in,".")+1) === "js" ? "script" : "style"; 
  header('link: <'.$in.'>; rel=preload; type='.$pushType,false);
  return $in;
}

add_filter('autoptimize_filter_js_exclude','pushJQuery');
function pushJQuery($in) {
	if (strpos($in,"js/jquery/jquery.js")!==false) {
	  	$jQurl=includes_url("js/jquery/jquery.js");
	    header('link: <'.$jQurl.'>; rel=preload; type=js',false);
	}
}

I think that if we're HTTP/2 pushing, we would also want to remove the defer flag from the autoptimized JS, OR go for "look only in head"+"force in head" for JS.

Contributor

zytzagoo commented May 31, 2017

My (simple) takeaway is to keep things on 1.1 still for now, it's pretty messy... and things can actually end up being slower.

But, really, the article is a must read. Especially about the preload/push distinction.

I went through all this topic a few months ago and now. I have been using the code based on trajano's comment on 21 Aug 2016. It has been spitting quite a big header. I have removed the images and focused only on css and js and then I had (among others) such headers sent:
<//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js>; rel=preload; as=script,<//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js>; rel=preload; as=script,<//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js>
... and so on.

The new code from futta's comment on on 31 May 2017 displays only AO files.

Does the push specification allow for 3rd party files in the headers? Does it make sense at all?

I took a look at what other popular sites are doing with server push and I noticed in the headers sent by akamai.com:

Link: https://www.googletagmanager.com;rel="preconnect",https://www.google-analytics.com;rel="preconnect",https://www.googleadservices.com;rel="preconnect"

So maybe it is not so bad idea? Is there any way to get also other js files by some smart filters in AO 2.2?

Owner

futtta commented Jul 28, 2017

well, preconnect is not HTTP/2 push, it's "just" telling the browser to already create a HTTP-connection to those domains :-)

regarding how many files to HTTP/2 push; only time (and testing) will tell, but from what I've read, heard & discussed one would not want to push all files, but limit the push to those files that are needed for the immediate rendering and leave the rest to normal loading?

trajano commented Jul 28, 2017

kevin25 commented Sep 2, 2017 edited

Do you have idea about this warning? Looks like the push server doesn't work out.

The resource /wp-content/themes/flatsome/assets/css/fl-icons.css?ver=3.3 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it wasn't preloaded for nothing.
08:59:09.128 (index):1 The resource /wp-content/themes/flatsome/assets/css/flatsome.css?ver=3.3.8 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it wasn't preloaded for nothing.
08:59:09.128 (index):1 The resource /wp-content/themes/flatsome-child/style.css?ver=3.3.8 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it wasn't preloaded for nothing.
08:59:09.128 (index):1 The resource /wp-content/themes/flatsome/assets/css/flatsome-shop.css?ver=3.3.8 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it wasn't preloaded for nothing.

Owner

futtta commented Sep 2, 2017

@kevin25 see some of @trajano's replies above; looks like chrome will (re-)download HTTP2-pushed resources if those resources aren't added by JS, so preloading normally linked CSS will probably see Chrome consider those preloaded files as useless.

kevin25 commented Sep 2, 2017

@futtta So any solution for this?

Owner

futtta commented Sep 2, 2017

trajano commented Sep 3, 2017 edited

You just need to know what the scripts would load (which is not really an easy thing to do in a general automated fashion)

Some candidates for this would be local fonts which can passed using preload and HTTP Push. Below-the-fold CSS can also be preloaded while the above the fold CSS is still part of the HTML that gets originally sent.

Lastly another candidate for preload would be the Ad network CSSes which are generally loaded via script.

In order for this to work well you need to have them part of the header rather than the body because if it is in the body then it will have to read a few bytes in and parse before it can do anything. You still need it in the body to actually be used by your page though.

The hack I did for this on an earlier version was to create a ".headers" file that gets sent if it is found and have a rule in the Apache configuration.

kevin25 commented Sep 4, 2017

@futtta Do you have any sample?

Owner

futtta commented Sep 4, 2017

trajano commented Sep 4, 2017 edited

@kevin25 http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml but I don't recommend it for anything above the fold. (i.e. anything shown on the first page before you scroll)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment