Flashing between page loads - javascript

On a website, I'm experiencing a "flash" of white that occurs between page loads. It looks bad because I'm using a background image and when the page loads, the background images flash before it comes onto the screen (take a look for yourself). This issues occurs in chrome and IE but not in firefox.
The site has a way of preloading stuff. Every element on the page is in a div wrapper #website which is initially at display:none, and every image is in a div wrapper #website-images which is also hidden. Then the site (using a jquery plugin) checks to see if all the images in #website-images are done loading, once they are a cookie is set to remember that this user has loaded the images already so it won't go through the preloading process once they go to another page or reload the current one, then a call to $("#website").show() is made to display the webpage.
So what could be causing this flickering between the page loads? Is it my way of preloading images? I've added different doctypes, and changed meta information but NOTHING has worked. I'm really lost here, does anyone have any ideas or insights?

This is happening because the DOMLoaded event is fired enough milliseconds before the page actually renders.
In a nutshell, this means you have to optimise your website's speed. This doesn't mean to make it download faster, but it means to download in the correct order, in a non-blocking way.
Step one: Your markup
1)
It seems there is a lot you can do to optimise your markup. Firstly, the order of stylesheets and JavaScripts can be optimised. To ensure CSS files are downloaded asynchronously, you always have to include external CSS before external JavaScript files. style.css is downloaded after some/all of your JavaScript calls.
There is 1 script block found in the head between an external CSS file and another resource. To allow parallel downloading, move the inline script before the external CSS file, or after the next resource.
2)
Your main JavaScript file is inline within your markup. Not only does this block the page download until the script has finished downloading, but having it before your content is probably causing (or adding to) the white flash.
Loading your script asynchronously in the head is my preferred method. You will then have to trigger your script when the DOM has finished loading, or you can achieve the same result by placing the script at the bottom of the body tag.
Step two: Harness the browser's capabilities
1) Looking at the http headers, there are 28 items being served as separate HTTP calls, that are not being cached on the browser (including the html pages, jpg images, stylesheets and JavaScript files).
These items are explicitly non-cacheable, and this can be easily fixed by editing your webserver's configuration.
2) Enable gzip compression. Most web browsers (yes, even IE) supports gzip decompression, and most (if not all) web servers support compressing using gzip. You could even go overkill and look into SPDY, which is an alternative lighter HTTP protocol (supported in Chrome and Firefox).
Step three: Content serving
There are around 30 individual items being served from your domain. Firstly, consider how you could reduce this number of requests. 30 HTTP requests per page view is a lot. You can combat this using the following methods:
1) Paralleled downloads across multiple hostnames. Browsers currently limit the number of concurrent connections to a single domain. Serving your images from a separate domain (for example, img.bigtim.ca) can allow them to be served in parallel to other content.
2) Combine multiple items into one. Many items that are downloaded are purely style content, such as the logo, menu elements, etc. These can be combined into a single image (downloaded only once), and split using CSS. This is called CSS spriting. Stack Overflow does this: look here.
3) If you cannot reduce the amount of items needing downloading, you could reduce the load on your server (and in turn, the client's browser) by serving static content from a cookieless domain. Stack Overflow does this with all their static content such as images, stylesheets and scripts.
Step four: Optimise your own code
There's only so much that HTTP and browser technology can do to help your website's speed. This last step is down to you.
1) Is there any reason you choose to host jquery yourself? Jquery's download page shows multiple CDNs where you can point to for speedy, cached script downloading.
2) There are currently over 20 unused CSS rules within your stylesheets (that's 36% of your entire CSS file). Have a re-think of what is really needed.
3) The main chunk of JavaScript (at the top of your body tag) seems to be a hack to attempt to speed things up, but is probably not helping anything.
A cookie is being set to specify whether or not the page has faded in yet. Not only are you using JavaScript to perform a transition which can happily be performed by CSS, but more than half of the script is used to define the functionality for reading and writing the cookie.
Seeing things like this: $("body").css ("background-image", "url('images/background.png')"); and $("#website").show (); usually gets me ranting about "separation of concerns", but this answer is long enough now so hopefully you can see that it is bad practice to mix style and functionality in the same code.
Addendum: Looking at the code, there is no need for jquery at all to
perform what you are doing. But then again, there is no need to
perform what you are doing, so you could probably do better without any
JavaScript at all.

Move your javascript to the end of the html just before closing the body tags. Sometimes it helps.

I know this is old thread but here is a hack I tried and works.
The idea is not to display anything while CSS is loaded completely.
in html file:
<body style="display:none">
in your CSS, the last line:
body{display:block !important}

CSS is render-blocking.
Divide you CSS into 2 parts -
Critical CSS
Non-Critical CSS
Make Critical CSS load with the page. It should come embedded within the head tag.
Make Non-critical CSS lazy load via ajax.
This will result in serious performance optimization in your webpage leading to less white-screen time.
Also, you can consider loading your Javascript in async/defer way.

Related

The difference between async loading js files and loading in footer [duplicate]

Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?
Put Scripts at the Bottom
The problem caused by scripts is that
they block parallel downloads. The
HTTP/1.1 specification suggests that
browsers download no more than two
components in parallel per hostname.
If you serve your images from multiple
hostnames, you can get more than two
downloads to occur in parallel. While
a script is downloading, however, the
browser won't start any other
downloads, even on different
hostnames. In some situations it's not
easy to move scripts to the bottom.
If, for example, the script uses
document.write to insert part of the
page's content, it can't be moved
lower in the page. There might also be
scoping issues. In many cases, there
are ways to workaround these
situations.
An alternative suggestion that often
comes up is to use deferred scripts.
The DEFER attribute indicates that the
script does not contain
document.write, and is a clue to
browsers that they can continue
rendering. Unfortunately, Firefox
doesn't support the DEFER attribute.
In Internet Explorer, the script may
be deferred, but not as much as
desired. If a script can be deferred,
it can also be moved to the bottom of
the page. That will make your web
pages load faster.
EDIT: Firefox does support the DEFER attribute since version 3.6.
Sources:
http://www.w3schools.com/tags/att_script_defer.asp or better:
http://caniuse.com/#feat=script-defer
All scripts should be loaded last
In just about every case, it's best to place all your script references at the end of the page, just before </body>.
If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="my.js" type="text/javascript" defer="defer"></script>
Edge cases
There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.
Further caveats
There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.
Only load jQuery itself in the head, via CDN of course.
Why? In some scenarios you might include a partial template (e.g. ajax login form snippet) with embedded jQuery dependent code; if jQuery is loaded at page bottom, you get a "$ is not defined" error, nice.
There are ways to workaround this of course (such as not embedding any JS and appending to a load-at-bottom js bundle), but why lose the freedom of lazily loaded js, of being able to place jQuery dependent code anywhere you please? Javascript engine doesn't care where the code lives in the DOM so long as dependencies (like jQuery being loaded) are satisfied.
For your common/shared js files, yes, place them before </body>, but for the exceptions, where it really just makes sense application maintenance-wise to stick a jQuery dependent snippet or file reference right there at that point in the html, do so.
There is no performance hit loading jquery in the head; what browser on the planet does not already have jQuery CDN file in cache?
Much ado about nothing, stick jQuery in the head and let your js freedom reign.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.
Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.
In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.
Just before </body> is the best place according to Yahoo Developer Network's Best Practices for Speeding Up Your Web Site this link, it makes sense.
The best thing to do is to test by yourself.

Modifying HTML while document is loading

Assume you have 75 div's that have data-id="{some number}" attribute. The overall page size is unfortunately big, very big.
There are many repetitive HTML snippets in my HTML document like image tags or links. These images/links' only changing portion is the id.
The HTML document is quite long, these snippets contribute to the overall size of the document.
I can run a javascript when dom is ready, but the user experience will be:
- wait the page loads, and start seeing nodes etc,
- page loads,
- extra snippets show.
I can make the top container DIV to hide until the page loads but
- worried that google search bot could realize the div is hidden and skip the content (or does it?)
- the users won't be able to see the content while the page is loading.
What ideal is to load the page in HTML without much extra markup for google search bot, and add extra elements while it's loading with javascript.
Any tricks that I can try that comes to your mind to accomplish this?
Thank you.
The best performance and user experience is to do as much work as possible on the server, then send efficient HTML and allow the browser to display the page as it's received. Sending say a single DIV container, then using script to clone it 70 or 80 times will be slower (probably a lot slower for some users).
Hiding content completely until your script has finished is the worst solution - users are left with a blank (or minimal content) page, waiting for something to happen.
The vast bulk of most pages is script and images, replacing HTML with scripting really is playing at the margins. e.g. this page has 90KB of HTML and 264KB of script, images and css. Apple's home page has 12KB of HTML and around 800KB of script, css and images.
Browsers show content progressively as it's received because that's how they evolved over many years on the web. Users prefer to see something rather than nothing, and to start viewing content while the rest loads (it's all about the content, not about fancy layouts or effects). Try to work with browser behaviour and features rather than against them.
You can greatly help the browser by specifying sizes for images and having an efficient layout. That way the layout won't change much as new content is received.
Depending on other page content, you could run your script on DocumentReady as opposed to onload.
DocumentReady runs after the page downloaded and the DOM rendered, but before images are retrieved.
I believe that there is an official DocumentReady event somewhere, but I still have to support IE6 on my pages, so I use a busy loop to watch the DOM.

Benefits of loading JS at the bottom as opposed to the top of the document

What are the real benefits (if any) to loading your JS at the bottom of the document, as opposed to the top. It seems there is a brief delay in page loading and JS dependent functionality.
I am using html5boilerplate for beginning all my templates, but am not really sure on how beneficial loading the JS at the bottom is.
Does it really make all that much of a difference, and if so, why?
If you include external js files at the bottom of your page, you give the priority of your HTTP requests to the visual display that will be presented to the client instead of to the logic of interaction or dynamics. I believe, if you do not use a content delivery network to deliver images to the client then you are only allowed to process a maximum of 2 HTTP requests at a time. You do not want to waste these requests on logic because we all know how impatient the end user is.
By loading js at then end of the file you can access the DOM(most of the time) without having to call a document.ready() function. You know that if the page render finally makes it to your javascript code that the necessary page elements have usually loaded already.
There are a few more reasons out there but these are the important ones that I try to remember when it feels so awkward to place all js at the bottom.
As scripts that are referred to are being downloaded, browsers typically won't download other files in parallel, thus slowing the page load.
refer: Best Practices for Speeding Up Your Web Site
A Google search will return a large number of results as to why you want to do so and what improvement you'll see. Check out some of these following links:
High Performance Web Sites: Rule 6 - Move Scripts to the Bottom
Rails Best Practices: Scripts at Bottom
Basically, the main reason for doing so is that you'll improve render times of your page. From the first article:
[I]t’s better to move scripts from the
top to as low in the page as possible.
One reason is to enable progressive
rendering, but another is to achieve
greater download parallelization.
depending on what is in the js. if only want it to 'go' when the page loads either surround your code by jquery's: $(function(){}) or place it at the bottom of the page

Optimal location for javascript includes

I've read that it is better to place your <script> tags at the end of the document. The argument for doing this appears to be that the browser will stall rendering the page below a script tag until it has loaded and and executed the script. If your script tag is at the top of the page, rendering is stalled for a while, which is bad.
However, I am not sure if this is really true any more.
Looking around, I normally see the following locations...
In the <head> of the page or Just inside the <body> tag
Stackoverflow is an example of a site that puts the script tags in the head, and since they are normally rather obsessed with performance, I am starting to wonder if position in the page is important at all.
Last thing in the body element
The other common place to put javascript appears to be right at the very end of the <body> element. I am assuming this means that the page can render while the javascript downloads and gets on with doing its thing.
But which is better?
Does anyone have any thoughts or advice on this? I am looking to try and get our pages to perform and appear to the user as quickly as possible.
Does it matter? What are the advantages of being at the top of the page? Bottom of the page?
It really depends.
There is no catch all answer for this because it depends on what your javascripts are acting on.
Putting scripts at the end of the page is sometimes needed if your acting on a DOM element that needs to be loaded for the script to run. Say you want to focus on a control and your script is:
var mytext = document.getElementById("mytext2");
mytext.focus();
Well in this case you would want it to execute at the end of the page, after mytext2 control has already been loaded by the browser. This is less important for script blocks that only contain functions that are called by events.
If you have a big .js file that contains libraries of functions you may also want to put that at the end of the page so the browser will load the page faster before loading the large .js file.
Google analytics suggests putting their tracker at the end, to make sure the page has been delivered before you count the hits, but in some cases it suggests putting the script into the header too, it works both ways.
So, rule of thumb for me is, HEAD scripts for everything except things that execute in-line and act on DOM objects, or large scripts that you want to load after the page.
Rick Strahl just wrote a great blog on placement of Javascript in .net too:
The only validating way is to include it on the top (in the <head> section), but in the bottom will be faster to load - the rest of the page will load faster if you have script near the bottom, giving the user better response and making the experience better.
The problem is that most web browser stop rendering the HTML of the page until they've fetched and parsed all JavaScript code so far. So if you have a slow-loaded .js file included in the <head>, no HTML will be rendered and images will not even start to download before the .js have been downloaded and parsed, therefore frontend engineers propagate for putting the scripts as far down in the code as possible.
I usually just set a far-future Expires header for my .js files so they are cached in the browser for a long time and then include them in the <head> section. This gives good performance and doesn't look ugly :-)
But if you are serving external .js libraries (that are on other servers than your own), you will probably want them in the bottom because you can't change the Expires-header for other servers and you canät know that the other server always will be responsive.
yeah. Put Scripts at the Bottom
I think the size of the js file is much more important than the location of javascript. I always set highter number of the con-current connection to make sure they download in parallel.
I believe it's better to place script tags just before the closing body tag. Because:
Elements are blocked from rendering if they are below the script.
In IE6, IE7 resources in the page are blocked from downloading if they are below the script.
From this article. Also Yahoo's performance rule 6 is Move Scripts to the Bottom
Google Analytics always used to say to put the script tag at the bottom of the page. I believe the rationale was that if the Google servers ever went down, the page would fail to load if it were in the head (only for IE probably).

Why are JS scripts usually place in the header of a document?

Why are JS scripts usually place in the header of a document? Is it required by standards, or is it just a convention with no particular reason?
See http://developer.yahoo.com/performance/rules.html#js_bottom
Although past practice has often been to place them in the header for the sake of centralizing scripts and styles (and the like), it is advisable now to place the scripts at the bottom to improve loading speed of the rest of the page.
To quote:
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
A <script src="url"></script> will
block the downloading of other page
components until the script has been
fetched, compiled, and executed. It is
better to call for the script as late
as possible, so that the loading of
images and other components will not
be delayed.
It depends on what the script is doing. If your code is wrapped in onLoad event then it doesn't matter since it will return almost immediately and not block otherwise you should put it where it fits because the placement does matter.
As for putting it at the end, it does give a little extra time for user to start looking at the page. Just ask yourself a question - does my site work without javascript? If it doesn't, then in my opinion it doesn't mater where you put it since onLoad code will only be executed when the DOM has been fully loaded (that includes binary content like images). If you can use it without javascript then put it at the end so that images can load faster.
Also note that most JS libraries use special code which works around the onLoad problem and uses custom event for this which gets fired once DOM has loaded and doesn't wait for binary data.
Now that I wrote all that, I got a question of my own. Does using say jQuery's
$(document).ready(function () {});
and putting the script tag at the end of page is the same as using onLoad event and putting it at the start?
It should be the same because browser would load all images before loading the script which is the last one in the list. If you know the answer leave a comment (I'm too lazy and it's too late to test it atm).
It's just a convention. It's usually recommended to put scripts at the end of the body so the page can display before loading them, which is always a plus. Also, document.body can't be used until the document is loaded or if you put the script in the body.

Categories

Resources