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

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

You could use media queries inside your stylesheet to determine if the display is a retina display, then load in the required CSS.
http://css-tricks.com/snippets/css/retina-display-media-query/
http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/

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.

How to make sure that all css and js files in web page or android app are loaded?

I have developed a mobile application which loads 3 css and 7 javascript files. Problem is if the wifi signal is very slow, HTML loads before all javascript and stylesheets are loaded. Since stylesheet is not loaded, HTML looks disturbed and after few seconds (i guess after css and js are loaded properly), HTML structure automatically take correct format but I dont want to show the disturbed format and to do that I need to make sure that all js files are loaded first then only HTML should display.
If you have any idea how can this be achieved ?
You can do using Cache manifests. Read these resources:
http://appcachefacts.info/
http://en.wikipedia.org/wiki/Cache_manifest_in_HTML5
https://developer.mozilla.org/en/docs/HTML/Using_the_application_cache
Alternatively - ensure your resources are loaded before the body by placing them in the right place (head tag).
You should link to your external css stylesheet at the top of your webpage in the header like this:
<link rel="stylesheet" type="text/css" href="http://whiterootmedia.com/css/example.css" />
or insert your <style> element in the header. Likewise this should be done for your JavaScript if it effects your initial layout. Keep in mind that if you are using an external JS file, the browser will stop rendering your page at the point in your code where your external JavaScript file is referenced, to load that external JavaScript file. If you're using a lot of JavaScript, place it at the bottom of your page (contrary to what most people do) or use an onload() function.
The webpage is loaded top-to-bottom, so the problems you're having should be related to the order of your css (most likely).

javascript lazy loading the progressive enhancement way?

I'm building a website for a gallery owner that has a lot of images per webpage.
Therefore I want to lazy load the images on the webpage, making the initial load
less heavy. However, I would like to implement this in a "progressive enhancement" way.
I've found a lot of lazy loading methods but they all require fiddling with the html code
in such a way that the webpage would be useless with javascript turned off. (eg. the src attribute of the img tags remains unset until the images is lazy loaded).
To implement a lazy loading method progressivly I think one would need the following:
prevent the browser from fetching the images, even though thers are on the page,
but only do this when javascript is on (so on non-javascript browsers, the images still
load as normal). This should be done without altering the html.
save the src attribute in a data-src attribute
sequentually load the images when scrolling down
Of these three steps the first one seems the hardest one. Even this stackoverflow discussion did not provide an answer that doesn't ruin progressive enhancement.
Has anyone got any ideas?
Since none has come up with an answer, I'll post what I found a reasonable solution.
This problem boils down to the following: while we want to prevent the browser from downloading the images when javascript is turned on, we must be sure the images are downloaded
when javascript is turned off or not available.
It is hard to consistently use javascript to stop loading images on a page when they are
in the "normal" format:
<img src="path/to/image.jpg"></img>
To stop the images from downloading we'd have to remove their src attributes, but in order
to do this, the DOM should be loaded already. With the optimisations a lot of browsers have nowadays it is hard to guarantee that the images aren't downloading already.
On top of that, we certainly want to prevent interrupting images that are already downloading,
because this would simply be a waste.
Therefore, I choose to use the following solution:
<img data-src="path/to/image.jpg" class="lazy"></img>
<noscript>
<img src="path/to/image.jpg"></img>
</noscript>
Notice how the images outside of the noscript tag have no src but a data-src attribute instead. This can be used by a lazyloading script to load the images one by one for instance.
Only when javascript is not available, will the images inside the noscript block
be visible, so there's no need to load the .lazy images (and no way to do this, since
javascript is unavailable).
We do need to hide the images though:
<noscript>
<style>
.lazy {
display: none;
}
</style>
</noscript>
Like the img tags inside the noscript block, this style block will only be visible to the browser when javascript is unavailable.
On a related note: I thought I could reduce the html size by not putting a src or data-src attributes on the lazy images at all. This would be nice because it eliminates
the redundant url from the page, saving us some bandwidth.
I thought I could pluck the src attribute out of the noscript block using javascript anyways. However, this is impossible:
javascript has no access to the contents of a noscript block. The above scheme is therefore
the most efficient I could come up with.
Not specifying a src attribute is invalid HTML, which is unfortunately how most lazy image loaders work.
I am working on a lazyloader that uses valid html markup, github link:
https://github.com/tvler/lazy-progressive-enhancement
A lazyloaded image would be declared by wrapping it in a noscript element:
<noscript><img alt="hello!" src="..."></noscript>
and the final outputted html would be
<img alt="hello!" src="...">.
You can view the whole project on github, which deals with batch loading, event hooking & more, but here's the basic functionality at the scope of a single noscript image:
var noscript = document.querySelector('noscript'), img;
(img = document.createElement('div')).innerHTML = noscript.textContent;
noscript.parentElement.replaceChild(img.firstChild, noscript);

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

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

Flashing between page loads

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.

Categories

Resources