How to reduce delay of "Onload"? - javascript

I'm current using a javascript with the this tag
<body onload="javascript:Mine();">
Now i noticed that it is taking some time to load this function after i open the page.So is there any other way i can reduce this delay ?
Thanks

onload fires when a page is completely loaded. To get things to fire sooner you can either:
Make the page load faster
Remove, reduce and optimize images (and other content, third party adverts are often a major performance kicker)
Follow performance guidelines (such as those from Yahoo!.)
Not use onload
Use a library (such as YUI or jQuery) that provides a domready event
Run the script in a <script> directly (instead of assigning an event handler)

OnLoad waits for all images and other external resources to be completely loaded. If you only want to know that the entire DOM tree with all HTML elements have been loaded, use OnDOMReady.
Note that this is not a trivial task if you want it to work well across many browsers. If you're using jQuery, then they've solved the problem for you, and you can write:
$(document).ready(function() {
Mine();
});
But if not, loading jQuery only for that feature might not improve your page load at all. Another solution, then, would be to put the call just before </body>:
<body>
...
<script type="text/javascript">Mine();</script>
</body>
Most of your DOM tree should be available to you at that point, so that might be a way to go.

Obvious answer: Speed up your page load.
onLoad means, that function will be run after your whole page has finished loading.

Related

Looking for an alternative to $(window).load that is slower than $(document).ready

I am trying to hide my preloader with JavaScript once the DOM and at least the top content has been loaded. The problem is that my page has several iframes which can slow the process down a lot.
My understanding is that if I use jQuery's $(document).ready to hide the preloader, it will be hidden too soon. On the other hand, if I use $(window).load, the waiting time may be too long. So, is there a middle-way solution, - kind of like window.load but without waiting for iframes?
EDIT:
My page has stuff like Facebook Like button Google Translate and a few other scripts that work via iframes. These are not critical elements, and I would not like to wait for them to load fully.
On the other hand, CSS files like Bootstrap, jQuery, etc. are curcially important for the presentation, and therefore to show the page (hide preloader) w/o having these loaded first would be premature.
Thanks.
You could use $(document).ready to determine if a particular element is loaded before hiding your loader.
Or if you have partial views, to have a $(document).ready function in one of those pages js do the loader hide job.
Since you did not provide more info, these are closer to guesses than real solutions.
I think you're looking for document.onload, which will fire when the DOM tree is ready. I believe that it fires before iframes, which all get their own onload callback/event handler.
You can also try placing the script tag at the end of your html file without begin inside an onload or ready function. This will cause it to load the html content, then fire the Javascript.
EDIT
A thought just occurred to me, which may or may not be useful. You probably have an idea about when you want your script to execute. In whatever browser you are using, check the network tab of the development console. There may be some other element's onload function you want to wrap your code in. For example, if you have a background image you want to make sure loads before your code executes, you may want to use it's onload.
As Petre said, lack of info in the question makes answering difficult.

Two different ways of putting the script at the bottom - what are the differences?

What are the differences between the two solutions below ?
In particular, is there a good reason to favour 2 over 1. (note: Please assume the name of the script to load is known. The question is just about if there is value in creating a minimal script to load a script in the given situation )
1 - Script At The Bottom
<html>
<body>
...
...
<script src='myScript.js'></script>
</body>
</html>
2 - Script at the bottom loads external script
<html>
<body>
...
...
<script>
// minimal script to load another script
var script = document.createElement('script');
script.src = 'myScript.js'
document.body.appendChild(script);
</script>
</body>
</html>
One important feature of the second one is that it allows the browser to finish parsing the page immediately, without waiting for the script to load. That's because the first example allows the script to use document.write to change the parsing state around the <script> tag, while the second one doesn't.
Now, we know that it's at the bottom of the page so that there isn't any important content left to parse, but this is still an important difference. It's not until parsing is done that the browser fires the popular DOMContentLoaded event. In method 1, the event fires after the script loads and executes. In method 2, the event fires before the script starts loading.
Here are some examples. In these demos, a DOMContentLoaded listener changes the background color to yellow. We try to load a script that takes 3 seconds to load.
http://jsfiddle.net/35ccs/
http://jsfiddle.net/VtwUV/
(edit: Maybe jsfiddle wasn't the best place to host these demos. It doesn't show the result until the slow-loading script loads. Be sure to click Run again once it loads, to see what happens.)
Pick the approach that's best for your application. If you know you need the script to run before DOMContentLoaded, go with method 1. Otherwise, method 2 is pretty good in most cases.
1. Script at the bottom
When you use a "synchronous" script tag, it will block the browser from rendering the page until the script is loaded and executed. This method has the following effects:
Regardless of where you put the script tag, the browser cannot fire DOMContentLoaded until the script is downloaded and executed.
Placing such a script tag at the bottom only ensures that the browsers has rendered all content before getting blocked by the script.
2. Script at the bottom loads external script
When you inject a script tag using JavaScript, it will create an "asynchronous" script tag that does not block the browser. This method has the following effects:
Regardless of where you put the JavaScript code that generates the script tag, the browser executes it as soon as it is available without blocking the page. The DOMContentLoaded fires when it should; irrespective of whether the script has downloaded/executed.
The second approach has the following advantages:
The script that injects a script tag can be placed anywhere including document head.
The script will not block the rendering.
DOMContentLoaded event does not wait for the script.
The second approach has the following disadvantages:
You cannot use document.write in such scripts. If you do, such statements might wipe the document clean.
Asynchronous execution does not mean that browser has finished parsing the page. Keep the script executes as soon as it is available clause in mind.
Execution order is not guaranteed. Example: If you load "library.js" and "use-library.js" using injected script tags, it is possible for "use-library.js" to load and execute before "library.js".
Having said all that, there is another method for loading scripts, with three variations:
<script src="myScript.js" async></script>
<script src="myScript.js" defer></script>
<script src="myScript.js" async defer></script>
Regarding Steve Souders's work: he proposed 6 techniques for loading scripts without blocking. The async and defer attributes introduced in HTML5 cover the Script DOM Element and Script Defer techniques and their browser support is more than enough for you to worry about the other techniques.
These two ways of initializing a script are basically the same, although theres no reason to use the second way if you can directly put in the result. However you can wrap the second example in a $(document).ready() method for example which would lead to sort of a lazy loading effect. This basically means that the page would load first and after the loading of the page is finished it would load the script. Or of course you can create a method which initializes a certain script this way. It's useful when you have a large script which is used only in some situations. This would prevent loading it unless you need it, thus decreasing the overall loading time.
This isn't a direct answer to your question, but it's good to know regardless.
The 2nd approach is sometimes used as a library fallback.
For example, you load jQuery from the Google CDN. But, if it were to fail for any reason, load jQuery from your own local copy.
Here's how the popular HTML5 Boilerplate recommends doing this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
The first method means that the script tag is hardcoded in. The second method dynamically adds a script tag to the bottom of the page using JavaScript. The benefit of the second method is that you can add additional logic if needed to modify the script tag. Perhaps you might want to load a different script file based on culture, browser or some other factor you can determine in JavaScript. The second method also causes the JavaScript file to be loaded without blocking the loading of the rest of the web page. In method one the page will stop loading when it gets to the script tag, load the JavaScript file, then finish loading the rest of the page. Since this tag is at the bottom of your page it doesn't make too much of a difference.
If you are creating a Windows Store app using JavaScript then the first method is recommended as this will allow the app to bytecode cache the JavaScript file which will make it load up faster.

Javascript: accessing DOM before document.onload

I have a page which has document.body.onload=function(){...} but this is suffering delays because the document also contains external <img> tags etc; onload seems to be only getting fired after these external sites have delivered some kind of response.
I put the code in onload because I thought the DOM tree wasn't fully available until then (e.g. document.getElementById(x) might return null if it is called too soon).
Is there an event which triggers after everything in the DOM is accessible, but before everything has been loaded?
You can just place your <script> tag at the end of the body since the html is parsed in sequence.
Additionally, you could look at jquery's document.ready. Even if you don't want to use jquery, you can have a look at how they handle it. ready does exactly what you're asking for.
Sure you can:
Maybe you have two options:
1)
by using jQuery:
with $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.
2)
DOMContentLoaded
Reference: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded
function checkDom(yourFunc)
{
window.addEventListener('DOMContentLoaded', yourFunc);
}
You should consider if you really need the whole document loaded. As long as your libraries are already loaded and the DOM nodes you are interested in are on the page, you can act immediately. This sort of code makes a page "come alive" much faster than one that waits for every last resource to load:
<form name="foo">
<!-- ... -->
</form>
<script>
var form = new My.FormWidget(document.forms.foo);
</script>
This has the added benefit of forcing you to encapsulate logic in the FormWidget (you should want to keep an "inline" script like that as brief as possible).

What to use in place of $(document).ready();?

So I'm using jquery along with some plugins I wrote.
I do all the initialization in a $(document).ready(function(){}) block however this is executed when the whole DOM has been loaded and is ready to be used.
However that would take long eg. when there is a server load. Or maybe the user clicks a button that has been loaded while the rest of the page hasn't loaded yet (and thus document.ready() hasn't been executed yet) in which case it would do nothing.
So, what if I want a code to be executed right after the related part of the page has been loaded instead of waiting for the WHOLE page to be loaded?
I know placing inline code right after the html that this js operates on would do the trick but what if that code uses a library like jQuery that hasn't been loaded yet?
I know placing inline code right after the html that this js operates on would do the trick but what if that code uses a library like jQuery that hasn't been loaded yet?
That would be the only way. The HTML is parsed from top to bottom. So you can expect every script you included to be accesible after you included it.
Your page should still work without JavaScript anyway, so a user clicking a button extremely fast will just temporarily have a somewhat degraded experience.
That being said, the DOM is basically ready when the HTML document all scripts are loaded. Since you cannot execute meaningful JavaScript before the JavaScript code is loaded (duh), I'd have a close look at page performance. Sending an HTML document and 2,3 JavaScript files should not be slow.
You could also use the old-style inline event handlers, like <button onclick="registerButtonClickEvent()">. However, this would introduce a complex, potentially buggy and hardly testable layer of temporary event holding.
If your <script src="jquery-whatever.js> line precedes the first clickable element in your HTML, it is guaranteed that the jquery library will be loaded and run before the user has anything useful to click on.
Just don't add async or defer attributes to the script element.
The onload event isn't triggered from all html elements, so you're forced to wait for window load. It doesn't matter where you load jQuery since it will have to wait for document to be ready. That total time required to load jQuery plus the rest of the document will be thet same.

Why call $.getScript instead of using the <script> tag directly?

I don't understand the reason for replacing this:
<script src="js/example.js"></script>
with this:
$.getScript('js/example.js', function() {
alert('Load was performed.');
});
Is there a particular reason to use the jQuery version?
The only reason I can think of is that you get the callback when the script is loaded. But you can get that callback using a script tag, too, by using the load event (or on really old IE, onreadystatechange).
In contrast, there are several negatives to doing it this way, not least that getScript is subject to the Same Origin Policy, whereas a script tag is not.
Even if you need to load a script dynamically (and there are several reasons you might need to do that), frankly unless you really need the callback, I'd say you're better off just loading the script by adding a script tag:
$('head:first').append("<script type='text/javascript' src='js/examplejs'><\/script>");
(Note: You need the otherwise-unnecessary \ in the ending tag in the above to avoid prematurely ending the script tag this code exists within, if it's in an inline script tag.)
script tags added in this way are not subject to the Same Origin Policy. If you want the load callback, then:
$("<script type='text/javascript' src='js/examplejs'><\/script>")
.on("load", function() {
// loaded
})
.appendTo('head:first');
(As I said, for really old IE, you'd have to do more than that, but you shouldn't need to deal with them these days.)
I can think of three reasons you might use the jQuery form:
You want all of your script declarations at the top of your document, but you also know that placing script declarations there forces the browser to download them in their entirety before proceeding further in the page rendering process. This can introduce measurable delay. The jQuery form will schedule the script loads until after the document is finished downloading, similar to the effect of placing all of your <script> tags at the end of the document, only without the syntactic weirdness.
The <script> mechanism is not available to scripts that do not live in the HTML document itself; that is, if a script included on the page with <script> wants to load a script, it has no option but to use a JavaScript-based approach, such as calling the jQuery function.
The jQuery form allows notification of the script's successful execution, in the form of a supplied callback function.
No need to do that..
You do that if you want to load the script dynamically (when needed, and not from the beginning)
The script might depend on jQuery, so it would be a way to prevent the browser trying to load it if it hasn't loaded jQuery.
There are a number of reasons that jQuery might not load, from a simple network failure to a CDN not being whitelisted by a NoScript user.
maybe to control when a script is loaded? On a javascript heavy page, it may be worth waiting to load some things that are non essential until after essential things are loaded.

Categories

Resources