Going "Stateless" and loading scripts dynamically - asp.net

What I want to know is if I am approaching this from the right angle.
I have an asp.net app I am building. I am using a Masterpage for the overall look of the app (below you can see the code).
I'd like to have the menu system use a dynamic load like jQuery's .load() function to load the content. That is fine and I have that down. The .load() function uses innerHTML to pump that content into the page. This is a problem if on that page you want to load module specific scripts and styles.
My question is, in an environment such as this, how do you guys load your scripts for these modules? Should I load every script on the initial load of the app? This app will not ever be "that big" however I want to make sure I do it right just in case.
MasterSheet
<div id="primaryNavigation">
<ul>
<li class="current">Main</li>
<li>Some Overview</li>
<li>Reporting</li>
<li>More Reporting</li>
<li>About</li>
</ul>
</div>
<div id="mainContentContainer">
<asp:ContentPlaceHolder ID="cphBody" runat="server" />
</div>
Example Module inside of the Content tag
<div id="container">
Inside a page
<script id="scriptToLoad" type="text/javascript">
alert('Something');
head.ready(function () { console.log('please print'); });
</script>
</div>
<div id="includeScripts">
../Files/Javascript/SomeModuleSpecificJs.js
../Files/Javascript/SomeModuleSpecificJs1.js
</div>
My idea was to set up a div in each module that would have the id of "includeScripts" and load those from a method within the mastersheet like this. This method works (needs some tweeking obviously) however if the user keeps clicking on modules eventually every file will be loaded. If thats the case I might as well load them all on the mastersheet.
JS to be ran when the MasterPage is loaded
$navigation = $("#primaryNavigation").delegate('ul li a', 'click', function () {
$('#primaryNavigation').find('li').removeClass('current');
$(this).parent().addClass('current');
$('#mainContentContainer').load($(this).attr('href') + ' #container');
// Obviously this would overwrite the content from the container, this is merely proof of concept
$('#mainContentContainer').load($(this).attr('href') + ' #includeScripts');
var jsArray = $('#includeScripts').text().trim().split("\n");
$.each(jsArray, function (index, value) {
$.getScript(value);
});
return false;
});

I don't know about .load(), but JQuery's .html(), .append(), and a few other related functions will automatically run any script tags that they find in the given HTML. If load() doesn't do that for you, it should be easy enough to use $.get(..., function(){$('#myElement').html();}); instead. You could even write your own extension specifically for this purpose.
Style sheets may be a different story. I've typically just used a single style sheet per page.
Edit
I just spent some more time reading your question, and I realized that I didn't answer it fully.
Should I load every script on the initial load of the app?
It really depends on the size of your scripts and the way you expect users to interact with your system. In this seminar, the people who made Google Wave talk about how they addressed this issue. At one point the speaker says, "Perceived latency is the most important thing to optimize for." The problem was, in an early version, their javascript file (optimized and compiled by GWT) was a few megabytes in size. People with a slow connection (a cell phone browser, e.g.) would have to wait a long time for all this code to download before they could see what was in their Inbox. Their solution was to create "split points" in their code so that it could be loaded in chunks. The code necessary for displaying the Inbox could be loaded first, whereas the Contacts panel could wait until the user clicks "Contacts."
But you can take this too far. The other speaker in this video says the time spent in loading falls largely under one of two categories:
Fetching data you don't need, and
Too many HTTP requests
Each HTTP round-trip involves a certain amount of overhead, so it can be worthwhile to load some code you don't need yet in order to avoid having to make another round-trip in a few milliseconds when you realize you need it.
Since you say:
This app will not ever be "that big"
... I'm guessing that you'll probably fall mostly under the latter category (too many HTTP requests). The best thing to do in that case is:
Use a tool like Chirpy to consolidate all your javascript files into a single file (which can be automatically minified when not in Debug mode).
If your application has a login page that doesn't use all this javascript functionality, add a script tag for this javascript file at the bottom of the login page so that the user's browser will download the file behind the scenes while the user is busy entering their username and password. The master page for the rest of the site should simply include the script file once in a standard script tag.
Make sure your site's caching rules are set up properly so that user's browser will only request this file once.
Make sure your site is set to compress this javascript file since javascript (especially minified javascript) lends itself to gzip compression very nicely.
Once you've done this, you should find that there is no "perceived latency" from loading your javascript file.
If your application does eventually become "that big," you'll want to break your program down into modules like the Google Wave team did. But choose your modules based on how you expect the system to be used. If only a small handful of users is likely to use your admin interface, for example, you'll want to put all of your admin UI code into a separate module that "normal" users will never have to download.
When deciding where to draw the line, UI experts basically say one-fifth of a second is the point where the typical human's brain starts wondering, "Did that work?" If a user clicks a button and has to wait longer than that before they see something happen, you've reached the point of "perceived latency." Anything beyond that will become increasingly annoying to the user.

Related

Removing render blocking JS and CSS causing issue in my WordPress website

i'm trying to improve speed of my website. i'm using PageSpeed Insights to check my site performance and it was telling me to remove render blocking java script and css. so i did it and know its causing problem in my website design. so what should i do to remove rendering blocking without causing problem in my website design.
Render Blocking CSS
Render blocking CSS will always show on Google Page Speed Insights if you are using external resources for your CSS.
What you need to do is to inline all of your 'above the fold' styles in <style></style> tags in the head of your web page.
I will warn you, this is NOT easy and plugins that claim to do this often do not work, it requires effort.
To explain what is happening:-
A user navigates to your site and the HTML starts downloading.
As the HTML downloads the browser is trying to work out how to render that HTML correctly and it expects styling on those elements.
Once the HTML has downloaded if it hasn't found styles for the elements that appear above the fold (the initial part of the visible page) then it cannot render anything yet.
The browser looks for your style sheets and once they have downloaded it can render the page.
Point 4. is the render blocking as those resources are stopping the page from rendering the initial view.
To achieve this you need to work out every element that displays without scrolling the page and then find all the styles associated with those elements and inline them.
Render Blocking JS
This one is simpler to fix.
If you are able to use the async attribute on your external JS then use that.
However be warned that in a lot of cases this will break your site if you have not designed for it in the first place.
This is because async will download and execute your JS files as fast as possible. If a script requires another script to function (i.e. you are using jQuery) then if it loads before the other script it will throw an error. (i.e. your main.js file uses jQuery but downloads before it. You call $('#element') and you get a $ is undefined error as jQuery is not downloaded yet.)
The better tag to use if you do not have the knowledge required to implement async without error is to use the defer attribute instead.
This will not start downloading the script until the HTML has finished parsing. However it will still download and execute scripts in the order specified in the HTML.
Add async in the script tag and put the css and js in the last of the page

Implementing cookies on a dismissible slide-in panel with AMP

I'm implementing a slide-in-on-scroll newsletter signup form on our site, which is built as AMP-native.
I added a button that hides the div on tap using amp-bind, but I'm struggling to get my head around how to save the closed state with cookies/localStorage in AMP.
I've gone through the favorite button example code - https://ampbyexample.com/advanced/favorite_button/ (as recommended here on SE), but I don't see how it relates to this particular use-case, especially with the use of amp-list.
Based on what I've read and few examples I found the credentials="include" attribute is needed, as is a valid CORS json endpoint and an auto generated client id appended to the endpoint url using AMPs variable substitution, but I'm not sure how to put it all together.
I took a stab hacking something together using the favorite button example, but the tutorial doesn't say much about how to setup the CORS endpoint and that particular example is for storing multiple likes to a single endpoint, as apposed to storing a specific users viewing preferences.
Here is my rough (poking-around-in-the-dark) stab at the code:
<form method="post"
id="side-newsletter-wrap"
action-xhr="/prefs&clientId=CLIENT_ID(prefs)"
target="_top"
on="submit:AMP.setState({
showSideNewsletter: !showSideNewsletter
});
submit-error:AMP.setState({
showSideNewsletter: !showSideNewsletter
});">
<button on="tap:side-newsletter-wrap.hide" class="close-button"><i
class="fa fa-times"></i></button>
<amp-list width="320"
height="360"
credentials="include"
items="."
single-item
src="/prefs&clientId=CLIENT_ID(prefs)">
<template type="amp-mustache">
{{#.}}
<?php winefolly_load_fragment('newsletter-embed'); ?>
{{/.}}
{{^.}}{{/.}}
</template>
</amp-list>
</form>
For the prefs endpoint, I'm guessing I'd need to register a new endpoint in WordPress that outputs simple array with the preferences?
Something along the lines of:
{
showSideNewsletter: "true",
winesIndexView: "grid",
winesIndexSort: "title"
}
I also tried the amp-user-notification component (which has the closed state built in) but that felt a bit hacky and the newsletter embed code (via iframe) doesn't get loaded due to a known bug - https://github.com/ampproject/amphtml/issues/18995).
Any suggestions would be much appreciated.
Chris
You're right amp-user-notification is the correct approach. Is there a way to implement the newsletter form in AMP until the amp-iframe bug is fixed?
Another way is to use amp-access, which allows you to change the layout of the page on page load. You have to store the user preference server-side though using the READER_ID to identify the user. Storing this server-side is required as you might not be able to write cookies if the page is served from the AMP Cache due to ITP 2.0.

jquery mobile 1.4.5 single-page template href querystring ajax

I am a newbie to JQM (I use 1.4.5) and my webapp (asp.net C# apache Cordova) contains many separate pages of .cshtml (single-page template) only. I am testing my webapp on a Samsung Galaxy Grand using Android 4.2.2
A.
I am not sure about my understanding of 'linking pages', even after reading all the JQM docs on this and also after reading up many, many posts on this topic about passing querystring values to another page; mainly because I find that ALMOST ALL the examples are directed towards providing answers for internal pages (Multi-Page template) within a single html page.
So I request some of you JQM experts to confirm or correct the following understanding of mine....
From the JQM docs I understood that
I could use in any link (e.g button), href="page2.cshtml?par1=1&par2=2"; and JQM will automatically use Ajax for this link to work.
I also understood that use of querystring is always allowed in such cases of different html pages of the same domain and it will work via Ajax automatically ; so long as the attr such as rel="external", data-ajax="false" etc. are not used in the same link.
but querystrings are not allowed in case of the internal pages (multi-page template) only....;
and if I need to use the above href to link to a page in another domain e.g. www.anotherdomain.com/page2.cshtml?par1=1&par2=2, then I need to use rel="external".
Are all my above points (that reflect my understanding) CORRECT? KIndly confirm ro please correct me ...
B.
In my app, I find that most of the links work according to my understanding as above, to connect to different pages in the same domain; and I assume it happens via Ajax. Is it correct? I am also able to use the querystring params in page2 ( i.e. To-Page).
But in one case, though it works, in the To-Page the Panel features do not operate correctly, unless I introduce rel="external' in the href link !!! I suppose it means it IS NOT AJAX anymore? Also I am unable to find the reason..
Further independent of the above topic, I face another issue. The loading time (i.e. Time taken to display the To-Page) varies.
Mostly it is OK, but at times the loading-circle goes on forever.... and I presume it has crashed....??? then If I go back using the back button and come forward again, many times it loads immediately...!!!!!
Any thoughts or suggestions.....?
Thanks in anticipation...
Ratna
Before you can worry about how to pass attributes from one page to another you need to understand the difference between multi-page and multi-HTML templates.
Multi HTML page template
Smaller and lighter, each data-role=”page” is inside a separate HTML file and page structure is much more modular.
Can become even smaller if every subsequent HTML page is stripped from HEAD content, or anything that isn’t data-role=”page” div. Unfortunately in this case fallback if JavaScript is not supported is out of question.
DOM size is relatively small, only first page is permanently loaded into the DOM, any other page will also be loaded into the DOM but at the same time it will also be removed when not used actively, basically each time you move from it.
Better fallback if JavaScript is not supported. Works great in desktop browsers after a page refresh, mainly because every HTML page has an existing HEAD content. This also allows your app to behave like normal web app mainly because AJAX can be turned off.
Multipage template
Since all pages are already loaded, no additional requests are generated for navigating between pages.
First load is slower as the file size is larger, but subsequent page navigation is fast, thus making transitions much more smooth. Almost native-like smooth, emphasize on almost.
Suitable for relatively smaller applications and situations where you know the capabilities of your target platforms including presence of JavaScript support, thus making it a great solution for a hybrid app. It works much better as a Phonegap app then multi HTML template.
The “page” data-role element is required.
More about this topic can be found here: Multipage template vs Multi HTML template in jQuery Mobile
Now let's talk about how to properly pass data between jQuery Mobile pages.
jQuery Mobile uses AJAX by default
You can turn off AJAX using rel="external"
If you turn off AJAX you will lose almost everything good about jQuery Mobile, including animations. So if you don't want AJAX page handling better find some other responsive framework like Bootstrap or Foundation.
If you don't want to use AJAX you can still use querystrings but inside a href or via changePage function.
Better querystrings alternatives:
Global object.
If you're using AJAX you can simply use a global object(s) to store all of your data.
Something like this:
// Store object
var storeObject = {
parameter1: null,
parameter2 : null
}
Access data from the previous page
Again if you're using AJAX you don't need to pass any data because all that data is till in the DOM.
// Store object
$(document).on('pagebeforeshow', '#second', function(e, data){
alert("My name is " + data.prevPage.find('#test-input').val());
});
Localstorage or Sessionstorage
This solution will work no matter if you use AJAX or not.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#change-page-button', function(){
// store some data
if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}
// Change page
$.mobile.changePage("#second");
});
});
$(document).on('pagebeforeshow', '#second', function(){
alert('My name is ' + localStorage.firstname + ' ' + localStorage.lastname);
// Lets change localStorage data before we go to the next page
localStorage.firstname="NewFirstNeme";
localStorage.lastname="NewLastName";
});
$(document).on('pagebeforeshow', '#third', function(){
alert('My name is ' + localStorage.firstname + ' ' + localStorage.lastname);
});
Send data through changePage function or via href
// Send
$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true});
or
Send parameter
receive that same data:
$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
If you need more information about this solutions including working examples find them here: Passing data between jQuery Mobile pages
Several methods mentioned here are deprecated (still usable) in the version 1.4. Though you don't need to worry about that, almost everything here will be unusable in version 1.5. This new version will overhaul jQuery Mobile from the bottom to the top.
Update
Yes, you can use any such link and jQuery Mobile will use AJAX. If you take a look at my previous examples you will find a working one.
If you want AJAX you CAN'T use rel="external", data-ajax="false" though stringquerys will work in bot cases.
Correct they will only work in multi-HTML template. Though there used to be a 3rd party plugin that allowed this to work with multi-page template but I don't think it works with newer jQuery Mobile versions.
Correct, if you want to link external page you need to use rel="external".

Efficiently reusing (poorly designed) JSON template for additional sites?

My supervisor just handed me a pile of JSON files from a freelancer which we are going to use to make multiple (similar) websites. Lucky me, I'll get to be the one updating the content and css for the different versions.
This is my first time working with JSON, so while I can't be sure that this is a poorly designed template, the fact that the css is very messy (in order to change the color of buttons throughout the site from yellow to orange, at least 15 different classes need to be adjusted, which seems to me to defeat the whole purpose of css...) doesn't give me hope.
I've brute-forced my way through the first two different sites, but since it looks like we'll be doing a lot more of them, I'm looking for ways to streamline the process (in particular making sure to change the content in all the places the content needs changing, which is a lot of files, with different content for different versions).
I'm personally old-school enough to like awk (well, that, and it's what I'm most used to programming in), so my backup plan is to just set up an awk/batch script or two which will take in a "these are the bits of info that go in these specific places" file and update all the relevant files. However, I'm sure there's a better way to do this, which is why I'm turning to y'all.
Is there anything that already exists for streamlining processes like these? Or a coding system/language that's well-suited to this project? A GUI which I can connect to bits of text that need changing?
Ideally, I'd like to set up something that even a monkey (or a non-caffeinated me) could use as often as needed. I'm already going to have to dive into the source code to clean it up (because, gasp, we might need to be able to have more than 5 people on the "our team" page, for example - without bad css/html workarounds), so making other tweaks that'll help with the content update process can happen en route.
I have recently used underscore to render templates from JSON. this is a front end tool, but you could automate it with some backend tools (a simple cURL or file_get_content in php will do).
Here is a link to a tutorial
your template will be a JavaScript template in your html file:
<div id="rendered"></div>
<script type="text/template" class="template">
<%- rc.listTitle %>
</script>
and in your JavaScript code you load:
<script type="text/javascript">
// When rending an underscore template, we want top-level
// variables to be referenced as part of an object. For
// technical reasons (scope-chain search), this speeds up
// rendering; however, more importantly, this also allows our
// templates to look / feel more like our server-side
// templates that use the rc (Request Context / Colletion) in
// order to render their markup.
_.templateSettings.variable = "rc";
// Grab the HTML out of our template tag and pre-compile it.
var template = _.template(
$( "script.template" ).html()
);
// Define our render data (to be put into the "rc" variable).
var templateData = {
listTitle: "Olympic Volleyball Players",
};
// Render the underscore template and inject it after the div rendered
// in our current DOM.
$( "#rendered" ).after(
template( templateData )
);
</script>

"Eliminate render-blocking CSS in above-the-fold content"

I've been using Google PageSpeed insights to try and improve my site's performance, and so far it's proven extremely successful. Things like deferring scripts worked beautifully, since I already had an in-house version of jQuery's .ready() to defer scripts until the page had loaded fully, all I had to do was inline that particular function and move the full scripts to the end of the page. That worked great.
But now I find myself glaring at the one remaining yellow dot on the checklist: "Eliminate render-blocking CSS in above-the-fold content".
The way my CSS is set up is to have one global _.css file containing styles that apply to the page structure in general, or are used in more than one or two places across the site. Most pages then have an associated CSS file (for instance, party.php has party.css) containing styles specific to that particular page. All CSS files are cached indefinitely, as I append /t=FILEMTIME to filenames (and later remove them with .htaccess) in order to guarantee that files are updated when they are changed.
So anyway, Google recommends inlining critical styles needed for above-the-fold content. Trouble is... well, take a look at this screenshot: http://prntscr.com/1qt49e
As you can see... ALL of the content is above-the-fold! People hate scrolling, especially on a game that involves loading many pages. So I designed the site to fit on one screen (assuming a good enough resolution). So that means... ALL of the styles apply to above-the-fold content! So... is there any solution? Or am I stuck with that yellow mark on an otherwise near-perfect score?
A related question has been asked before: What is “above-the-fold content” in Google Pagespeed?
Firstly you have to notice that this is all about 'mobile pages'.
So when I interpreted your question and screenshot correctly, then this is not for your site!
On the contrary - doing some of the things advised by Google in their guidelines will things make worse than better for 'normal' websites.
And not everything that comes from Google is the "holy grail" just because it comes from Google. And they themselves are not a good role model if you have a look at their HTML markup.
The best advice I could give you is:
Set width and height on replaced elements in your CSS, so that the browser can layout the elements and doesn't have to wait for the replaced content!
Additionally why do you use different CSS files, rather than just one?
The additional request is worse than the small amount of data volume. And after the first request the CSS file is cached anyway.
The things one should always take care of are:
reduce the number of requests as much as possible
keep your overall page weight as low as possible
And don't puzzle your brain about how to get 100% of Google's PageSpeed Insights tool ...! ;-)
Addition 1: Here is the page on which Google shows us, what they recommend for Optimize CSS Delivery.
As said before, I don't think that this is neither realistic nor that it makes sense for a "normal" website! Because mainly when you have a responsive web design it is most certain that you use media queries and other layout styles. So if you are not gonna load your CSS first and in a blocking manner you'll get a FOUT (Flash Of Unstyled Text). I really do not believe that this is "better" than at least some more milliseconds to render the page!
Imho Google is starting a new "hype" (when I have a look at all the question about it here on Stackoverflow) ...!
How I got a 99/100 on Google Page Speed (for mobile)
TLDR: Compress and embed your entire css script between your <style></style> tags.
I've been chasing down that elusive 100/100 score for about a week now. Like you, the last remaining item was was eliminating "render-blocking css for above the fold content."
Surely there is an easy solve?? Nope. I tried out Filament group's loadCSS solution. Too much .js for my liking.
What about async attributes for css (like js)? They don't exist.
I was ready to give up. Then it dawned on me. If linking the script was blocking the render, what if I instead embedded my entire css in the head instead. That way there was nothing to block.
It seemed absolutely WRONG to embed 1263 lines of CSS in my style tag. But I gave it a whirl. I compressed it (and prefixed it) first using:
postcss -u autoprefixer --autoprefixer.browsers 'last 2 versions' -u cssnano --cssnano.autoprefixer false *.css -d min/ See the NPM postcss package.
Now it was just one LONG line of space-less css. I plopped the css in <style>your;great-wall-of-china-long;css;here</style> tags on my home page. Then I re-analyzed with page speed insights.
I went from 90/100 to 99/100 on mobile!!!
This goes against everything in me (and probably you). But it SOLVED the problem. I'm just using it on my home page for now and including the compressed css programmatically via a PHP include.
YMMV (your mileage may vary) pending on the length of your css. Google may ding you for too much above the fold content. But don't assume; test!
Notes
I'm only doing this on my home page for now so people get a FAST render on my most important page.
Your css won't get cached. I'm not too worried though. The second they hit another page on my site, the .css will get cached (see Note 1).
Few tips that may help:
I came across this article in CSS optimization yesterday:
CSS profiling for ... optimization
A lot of useful info on CSS and what CSS causes the most performance drains.
I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools:
DevTools Can do that.
Check out the sections on Time to First Paint, repaints and costly CSS.
Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.
Off the question:
I second #Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.
Please have a look on the following page https://varvy.com/pagespeed/render-blocking-css.html .
This helped me to get rid of "Render Blocking CSS". I used the following code in order to remove "Render Blocking CSS". Now in google page speed insight I am not getting issue related with render blocking css.
<!-- loadCSS -->
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/cssrelpreload.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/loadCSS.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/onloadCSS.js"></script>
<script>
/*!
loadCSS: load a CSS file asynchronously.
*/
function loadCSS(href){
var ss = window.document.createElement('link'),
ref = window.document.getElementsByTagName('head')[0];
ss.rel = 'stylesheet';
ss.href = href;
// temporarily, set media to something non-matching to ensure it'll
// fetch without blocking render
ss.media = 'only x';
ref.parentNode.insertBefore(ss, ref);
setTimeout( function(){
// set media back to `all` so that the stylesheet applies once it loads
ss.media = 'all';
},0);
}
loadCSS('styles.css');
</script>
<noscript>
<!-- Let's not assume anything -->
<link rel="stylesheet" href="styles.css">
</noscript>
I too have struggled with this new pagespeed metric.
Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.
Combining all css into one file helped a lot. All my sites are back up to %95 - %98.
The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.
The 2019 optimal solution for this is HTTP/2 Server Push.
You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.
My site https://r.je/ has a 100/100 score for both mobile and desktop.
The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.
You can use HTTP/2 push by setting the Link header.
Apache example (.htaccess):
Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"
For NGINX you can add the header to your location tag in the server configuration:
location = / {
add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}
With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.
You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"
For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push
Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.

Resources