Can I Flush the Buffer Early Using ASP.NET? - asp.net

Best Practices for Speeing Up Your Web Site from Yahoo includes the following recommendation:
When users request a page, it can take anywhere from 200 to 500ms for the backend server to stitch together the HTML page. During this time, the browser is idle as it waits for the data to arrive. In PHP you have the function flush(). It allows you to send your partially ready HTML response to the browser so that the browser can start fetching components while your backend is busy with the rest of the HTML page. The benefit is mainly seen on busy backends or light frontends.
A good place to consider flushing is right after the HEAD because the HTML for the head is usually easier to produce and it allows you to include any CSS and JavaScript files for the browser to start fetching in parallel while the backend is still processing.
Example:
... <!-- css, js -->
</head>
<?php flush(); ?>
<body>
... <!-- content -->
Note the point at which the flush occurs here is after the head tag is written. This makes a lot of sense so the browser can begin loading images and scripts while the remainder of the page is rendered and served.
Is there a way to flush after the head (or any other part of the page) explicitly using ASP.NET?

You should be able to put the following in your page between the end of the head and the beginning of the body statement:
<% Response.Flush(); %>
However, be careful here in the event that you are using a script manager or any other kind of control that will register itself for output in the head section of the html.

You might want to explicitly set Buffer=true in the #Page tag at the top of the page as well to avoid Response.Flush() throwing errors.

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

How to remove 'Optimize CSS Delivery' message for my website.

I am using https://developers.google.com/speed/pagespeed/ to determine my page speed. I can see:
Your page has 11 blocking CSS resources. This causes a delay in rendering your page.
Approximately 5% of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.
http://jegeachi.com/…in-with-ajax/widget/widget.css?ver=3.1.7
http://jegeachi.com/…-form-validation/css/style.css?ver=4.9.4
http://jegeachi.com/…validation/css/fonts/style.css?ver=4.9.4
http://jegeachi.com/…rontier-post/frontier-post.css?ver=4.4.1
https://fonts.googleapis.com/css?family=Open+Sans&ver=4.9.4
http://jegeachi.com/…-and-share/assets/css/styles.css?ver=3.3
http://jegeachi.com/…more-without-refresh/style.css?ver=4.9.4
http://jegeachi.com/…includes/css/dashicons.min.css?ver=4.9.4
https://maxcdn.bootstrapcdn.com/…4.7.0/css/font-awesome.min.css?ver=2.4.2
http://jegeachi.com/…ular-posts/public/css/wpp.css?ver=4.0.13
http://jegeachi.com/…ootstrap/css/bootstrap.min.css?ver=1.0.1
I manually compress all these css files and still I can see same message. What should I do?
N.B: I am using wordpress and Apache server.
I would recommend loadCSS to load your CSS asynchronously in order to avoid render blocking.
<link rel="preload"> do this for you, but is not supported in all browsers.

Going "Stateless" and loading scripts dynamically

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.

Managing header templates?

I'm new to creating html pages etc - but am using VS 2008 just for the editing/intellisense capabilities.
My problem is I have a pure HTML only website (no ASP.NET) and have a fairly extensive header that has to be used in every page. It's frustrating to change the header parts of the HTML across all pages every single time it changes in one. Is there someway I can sort of 'include' the header part HTML in other HTML pages without having to manually cut-paste all-over?
Please note - I'm not using ASP.NET, so I CANNOT and WILL NOT be able to use Master Pages. Is there some other technique is what I want to know - so that when I change the header template in 1 place, it gets reflected in all other. I thought of inline frames, but not sure if that's a crappy way to do that and if it affects SEO
Take a look at Server Side Includes
They'll allow you to edit your header in the one file, which will appear instantly on all pages that include the header file.
Yes, take a look at SSI. Server side includes are a simple way to tell your web server to insert various things at various points in your HTML page.
Example:
<html>
<head>
<!--#include FILE="head.html" -->
</head>
<body>
</body>
</html>
If server side includes don't appear to work as expected, try renaming the page with a .shtml file extension.
Some web servers require that you name your file ".shtml" rather than ".html" in order to enable the parsing of your file.

External JS file in web user control?

In a html page we use the head tag to add reference to our external .js files .. we can also include script tags in the body .. But how do we include our external .js file in a web user control?
After little googling I got this. It works but is this the only way?
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "MyUniquekey", #"<script src=""myJsFile.js"" type=""text/javascript""></script>", false);
-- Zuhaib
You can also use
Page.ClientScript.RegisterClientScriptInclude("key", "path/to/script.js");
That's the way I always do it anyway
Yes this works too .. but why does all
the script gets dumped in the body and
not in the head??
There's a potential workaround for that here
That's kind of incorrect .. about needing the Javascript in the body.
A Javascript function would sit in the head unexecuted and not at all affected by the fact that elements are still to load.
Often there is a single call at the end of a page to start execution of scripts at the top.
(Other methods available)
The only reason that script gets dumped in the body, is because MS doesn't seem to give 2 hoots about JavaScript.
Shame, because forcing us all to use .NET proper, just makes the world full of sluggish pages that needlessly run back and forth to servers for the tiniest requirmenet.

Resources