Preload array of images for faster load - javascript

I read here in SO about preloading the array of images for faster loading of the web page so that when the application needs them to be shown, that would have loaded and can be shown instantly. But my doubt was where to include the code snippet:
at the bottom of page or
at the start (<head>)?
As, I also read that in order for fast loading one should include all the javascripts at the bottom.
Which will be a better way? Or do I have to compromise on both the ways?
The javascript code:
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
preload([
'images/bg.jpg',
'images/logo1.png',
]);
</script>

Even though all the other answers are inherently correct. They don't seem to address you directly.
Your script is not making use of any DOM elements. Which means that waiting for the DOM to load is not a concern at all.
The halt of the layout rendering while downloading a <script/> is always a concern (unless you use new HTML5 capabilities such as async), that's why they prefer to place it before </body>.
By placing it before </body>, your rendering will not be halted. Performance-wise, iterating such a tiny array may only be a micro-optimization.
By the way, you don't need to wrap the array in $() to use .each(), you should use $.each.
function preload(arrayOfImages) {
$.each(arrayOfImages, function(index, image){
$('<img/>')[0].src = image;
});
}

Generally, put your function calls and everything that you want to do after the page finishes loading inside
$(document).ready(function() {
// Handler for .ready() called.
});
(See Docs).
This also applies to your call to preload(...).
As you use $('<img/>')[0].src = this, the browser will cache the image according to this comment: Preloading images with jQuery
Edit: The position of the <script/> tag in your DOM tree plays only a minor role, as Konstantin pointed out.

The top and the bottom of the HTML page is relevant because that is how the browser reads your page. Stuff on the top gets done before the stuff on the bottom.
In regards to image pre-loading you should do it in the top of the page in the <head>. Why? Because you don't need to use it yet. The rest of the page isn't ready and chances are that the place where you want to put the image doesn't even exist just yet.
We usually put JavaScript on the bottom of the page because we want to do something when the DOM is ready. You can put it on the top as well! But you would have to NECESSARILY use the $(document).ready(function(){}); in order to be certain that it would work as intended.
So, initiate your pre-loads on the top (or by using window.onload) while the rest of the page is loading as well. You wont really get much benefit out of doing it on the top unless you do it using CSS or if you bind the load event of a particular div that occurs on the top of the page and pre-load your images there.

Why not making a DIV on the very begining of the BODY section and move that DIV outside of the visible area?

Related

How to wait for HTML to draw before javascript function runs

I am working on a webapp that involves adding and manipulating many html elements with javascript.
Here is an example of my problem:
function 1: change the text size of all 500 elements
function 2: scroll to element #350 based on the location of element 350 (pixels from top).
The problem is that sometimes it takes time for the css to redraw the elements at the new size, so when function 2 fires, it is not accurate and it will end up scrolling to the wrong place.
function 1 works by using jquery to change the content of the <style></style> element in the html head.
how can I make javascript wait for browser to finish drawing before firing without guessing with arbitrary timeouts?
You can make your jquery fire after the page has loaded by including your jquery functions inside of this:
$(function() {
//your functions
});
You can put your script tags right at the bottom of your page. This ensure your DOM has been loaded and also allows the user to perceive the page as quickly as possible! Fantastic news, particularly if your scripts take a significant amount of time to execute as you can put a lovely loading graphic in there as a placeholder for top notch UX! :)
Have a look at window.addEventListener("load" it s pure javascript
function load () {
alert("Window loaded");
}
window.addEventListener("load", load, false);

Is there any jquery to detect if the html tag was not closed? or page has not completely loaded?

I'm experiencing an issue (which I still need to fix) where my entire page does not load. It gets cut off in the middle of an element.
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
I was thinking of just putting <div id="end_of_page"></div> at the bottom of the page, and checking if that was rendered, if not, i'll know something went wrong and can reload to try again.
thanks!!
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
You can do that, yes. Put this in the head after including jQuery:
<script>
jQuery(function($) {
if (!$("#end_of_page")[0]) {
// Something went wrong, load again
location.reload();
}
});
</script>
You'll enter the body of the loop (and so, force a reload) if the end_of_page element doesn't exist as of when the jQuery ready event fires (which is meant to be when the page is done loading).
But: Better by far to figure out why your page is getting cut off half-way through and solve that. This sort of workaround is not a solution.
You can use
$(document).ready(function(){
// code here
});
that code will only run when the page has loaded. A convenient shorthand is:
$(function(){
// code here
});
assuming your jQuery object is $. To finish your requirement, you can have a variable that is set within the load function, then use a timer set at the start of the page to check for it. If it's not there, reload.
Personally, I think you should invest some time into figuring out why your pages only half-way (Firebug or the Chrome Inspector may help you do this, it might be a resource in your page that is causing it to hang, and since most HTTP requests are only made 2 at a time per hostname, it might be waiting for that to return before fetching the rest).
Might be a server-side issue OR some script or library is stealing your fish $ (AKA: 'Dollar').
I'll rather suggest you to debug your code instead of refreshing the page trying to fix issues.
Make sure your scripts are in the head of your document, and jQuery + your jQ functions right before the closing </body> tag wrapped in:
(function($){ /*your functions*/ })(jQuery);

Minor problem while loading page with jquery

I'm using the slidedeck jquery plugin which basically puts slides on my page. Everything works fine, but the problem is with the css loading part. Below these slides i have an import statement for another page. This page which i'm importing fetches quite a bit of data from the database before being completely displayed.
So whenever i open my page for a second or two the display for my page goes hay wire. The probable cause of this may be that i'm putting most of my jquery including the one for these slides in the document.onready function. So since the document is not loaded completely for that period of time slides are also not displayed. (as in they are displayed but in a weird manner......they are all over the page!!!!)
Is there some way i can make sure that my css and jquery get loaded first and then a call is made to this page which i'm importing or something like that. i just want that my display comes fine right in the beginning.
this is the slidedeck jquery plugin i'm using
slidedeck : http://www.slidedeck.com/
ahh i actually found a solution for my problem. Now what i'm doing is that i'm keeping the div (say id="slideDeckContainer") containing this slidedeck initially as hidden (using css style=display:none). Only after the page is done loading inside the $(document).ready(function(){....}); i call $('#slideDeckContainer).show(); on the div. (since the $(document).ready(function(){...}) is callled only after the page is loaded)
Definitely not the best solution but for now it works :).
instead of $(document).ready(function() { //code here }); you can use $(document).load(function() { //code here}); The load function fires after everything in the selector has loaded. In this case, we are selecting the document, so this function will run only after the CSS, javascript, and DOM have finished loading. Another suggestion is to give the DOM elements that you are loading content into a defined width and a height. This way, before the loading finishes, there will be space reserved for the loading content and it won't mess up your page layout.

Does it matter where JavaScript is placed on a html page?

I've messing about with html5, I've never really had a good look at JavaScript before.
I'm referencing script file like this (not in the head)
<script src="somthing.js"></script>
However the script only seems to work if it placed below certain elements on the page.
Are there particular situations when it matters where javascript is placed?
Thanks in advance.
If the script isn't waiting for an onload or "ready" event of some sort, it needs to be place after the elements it references (otherwise they won't be there to find). If you're unsure, stick it just before </body>.
In this case it looks like that's exactly what's happening, it's looking for elements that haven't been added to the DOM yet. Placing the script at the bottom of the <body> is one common practice to counter this. Some alternatives are using the window.onload event to run your code, or jQuery's $(document).ready() for example (most major libraries have some equivalent of this).
If your script is acting on an element it needs to either be placed after that element on the page or set up to execute when the page is finished loading. If the script runs before the element has been added to the DOM (which occurs when it is encountered as the browser parses the page), then the script can't find the element upon which you want it to act. Placing the script after the element ensures that the element is available for it to work on. Likewise, forcing it to run after the entire page loads makes sure that all elements are available to the script.
I'd suggest that, in so far as possible, you load your scripts right before the closing </body> tag. I would also look at using a framework, like jQuery, which makes it easy to run your scripts on page load complete and wrap the code inside it's load event.
The best practice according to Yahoo's Performance Rules is to place scripts at the bottom of the page:
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.
Well we'd need to know what was in your script to tell you really, but the short answer is "yes it does matter".
Scripts (essentially) execute when encountered by the browser. A classic blunder is to make a reference to a page element in a script placed earlier in the document than the element it references - when the script is executed the element doesn't exist yet!
It is generally considered appropriate to keep scripts in the head, the solution to the above problem therefore being to attach functional code to onload event handlers.
Bonus round: a much more subtle reason script placement matters is because most browsers will single-thread downloads when they encounter a script (for security reasons and because the script can modify the download requirements for example). This is one of the reasons yahoo recommends placing scripts last in your document, but it's a controversial thing to do for a subtle benefit of perception only.
YES it does.
for example, let's just say your js code is at the top. and it is interpreted before the browser is done setting up a section of the dom tree...in this case the HTML element that you are referencing, if referenced before it is available, will produce an error saying that the element is undefined.
Another reason is the user experience. If the css is at the top, when the html is displayed all looks good, but unless the js is at the bottom, you will have to wait for it to be loaded and be ready for execution before the rest is rendered; therefore, slowing down the rate at which items on the screen are rendered.
I see it a lot. Different strokes for different browsers, but just put the js at the bottom, and css at the top and you avoid having to worry about stuff like this.
It depends on what the script is designed to do. If it is using the document.write() method, then it does matter where it is on the page. If it's trying to reference elements in the DOM, it is best put in the HEAD and have those functions that access DOM elements triggered after the page is loaded.
There are a couple of scenarios where the placement is important.
Assuming you have a function call foo() in your_script.js and you call it before you include your_script.js, than it simply won't work because foo() isn't defined yet.
If the code requires a certain element to be available (for example, a lightbox script) than it is possible that loading the code before your lightbox image elements results in the lightbox not doing anything.
So basically... it depends very much on what scripts you are running. Sometimes it will matter, other times it won't.
Yahoo actually recommends putting your scripts at the bottom. The downloading of a JS file is a blocking action which means nothing else is downloading at that time (such as images/css) By putting your scripts at the bottom the user gets the html/images/css first and actually see the page faster, and your JS downloads after to add interactivity.
Having said that, as the other posts mention, your script has to wait until the dom is ready before actually doing anything to the DOM, otherwise you'll have varied behaviour depending on when the DOM is ready.
Well, here is what I think.
If you need to execute your script, before the HTML starts the render in the clients browser then it will be better to be placed in <head> section.
And if you are executing a JavaScript code which communicates with a element in some way then the script should be placed behind that element, because if the script starts ahead then it can't find its respective element to communicate with. So it is better to placed behind element.
This is not only about where the script is placed in the page, but also when the code in the script is executed.
Script tags normally goes in the head section of the page. However, that means that no elements are loaded when the code loads, and if it executed immediately you can't access any elements. The solution to that is to use the onload event of the page. Example:
<html>
<head>
<title></title>
<script>
function init() {
document.getElementById('message').innerHTML = 'Hello world!';
}
</script>
</head>
<body onload="init();">
<div id="message"></id>
</body>
</html>
Javascript libraries may have other methods of doing something similiar, like the ready event in jQuery.
You can place scripts in the page (although this is not what's recommended by the HTML standard), but if you need to access elements in the page from code that runs immediately, the script has to be loaded after the elements. Example:
<html>
<head>
<title></title>
</head>
<body>
<div id="message"></id>
<script>
document.getElementById('message').innerHTML = 'Hello world!';
</script>
</body>
</html>
Scripts may also be placed late in the page for performance reasons. You can keep that in mind and save it until you actally have any performance problems.
In simple terms : Make sure the element(s) the script accesses is loaded before the script starts executes. Ofcourse if you are unsure put it just before .
Your script likely attempts to operate on the DOM before it is ready. This should not be solved by moving it around, but rather by deferring execution with domready callbacks.
After that is sorted, you should aspire to keep script inside of head. It used to be a common practice to include scripts at the bottom of the page to avoid page- and request-blocking. In HTML5 such performance impacts no longer matter since you can take advantage of async attribute. It allows for the loading of JS files to be initiated without side-effects:
Traditional scripts block the HTML parser, preventing the rest of the page from being rendered until the script has been downloaded and run. Scripts using HTML5 async unblock the rest of the page so it can continue loading while the script is being downloaded. ^

if i'm using jquery library with some plugins should i place all at bottom , just before </body>

if i'm using jquery library with some plugins can i place all at bottom , just before </body> or it depends?
are there some situations where library+plugin should place in not at end of not bottom?
yes, place at the bottom of the page before </body> for fastest load time.
http://developer.yahoo.com/performance/rules.html#js_bottom
technically you could put it at the top of the page like Reigel is suggesting, but it locks up the whole page's execution, which is lame. the best idea would be to do it parallely, where you simply add the script as a DOM Node after the DOM has been loaded, if possible (if it doesn't mess up your page):
$( function(){ $( 'body' ).append( '<script src="plugin.js"></script>' ); } );
also, there is seriously a thread on this subject every week. search first.
As much as I know you should move JS from head to the body, as it does not delay of the page rendering itself, but the loading of other external scripts (css). I moved it to the bottom of the page, just to easily find it when looking at the source code..
The real reason behind putting everything at the bottom, right before the </body>, is so that your pages renders fast.
It is an optimization technique, that allows your page to show up in the browser before everything is loaded, if you put all your javascript at the top, the page will look blank until it has finishing loading the scripts, and the user will feel your site is very slow and probably leave.
So, it doesn't matter where you put it, it will still work, the difference is that you let your visitors, see some content and even click on a link even before all the javascript is loaded.
#Dan Beam: Placing your css at the bottom, might show the first render of the page in a weird way, because the CSS is not yet loaded.
<head>
<!--
.....
jquery should be at the top of all scripts... just the scripts
before you call
$(document).ready(function(){ .... });
-->
</head>
Document on how to setup.

Categories