Loading jQuery on window.onload? - javascript

i would like to load jquery.js after the window.onload event has been fired by browser (reducing load time)
Doing that maybe with appendChild the problem is i can't use anymore $(document).ready();
Is there a way to use something equivalent to .ready after the loading of jQuery (after the window.onload?)
thanks

Just place <script>s at the bottom of your HTML files. If you load jQuery right before the closing </body> tag, page rendering isn’t blocked while jQuery is loading.
It doesn’t matter if you speed up window.onload if you’re not gonna use it anyway. E.g. if you use…
$(document).ready(function() {
// …
});
…or its shorter alias…
$(function() {
// …
});
…internally it’s not relying on window.onload, but on DOMContentLoaded.
Loading scripts at the bottom is gonna help you much more than waiting for window.onload to start loading your scripts.

I think you can't. In order to use jquery as well as other plugins that developed from jquery, you have to load jquery.js first of all. (in the part, you have to put the script that load jquery.js on top)
It doesn't even work if you load (Slider, Thickbox, DatePicker...) first then jquery.js
^^

first of all load jquery from here
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
loading it from google means the user most likley already has it cached resulting in a much quicker load.
also to be honest jquery isnt that big a file (less than a meg) so it shouldnt really affect load times.

all script tags should be at the bottom of your page in anycase.. so loading times wont be affected.
content
script tags
otherwise you could do something like
if ($.jquery){
document.body. and then my js gets rusty... but basicaly append the script tag

Related

What is the event for </body> loaded, not document loaded in jQuery?

There are many good practices with document loaded:
$(function(){
....
}
The code above seems to wait for some extra resources to be loaded to run. At least I am quite sure it's waiting for the Google Adsense content to be loaded.
But what about the </body> loaded? Because sometimes there's no need to wait for the document loaded. I just want to immediately work on the DOM that is loaded. Is there any event can do that?
Update:
The code is like this:
<script>
// The script tag has to be above the a tag - which will be worked on later.
</script>
<a id="tobeworkedon">test</a>
</body>
I can't just move the script tag to the latter part. Can I still make it as fast as it were right before the </body> tag?
$(function(){
....
}
This method offers a way to run JavaScript code as soon as the page's DOM becomes safe to manipulate.
Simply if the browser supports, you can use
document.addEventListener('DOMContentLoaded', func, false);
For older browsers, you can try
document.attachEvent("onreadystatechange", func);
Maybe is this what you looking:
<body onload="myFunction()"></body>
But notice: It will fire uppon body loading, even if some images or resources are not loaded yet.

Speeding up website - marking scripts/images as optional?

On my website I have ads from a network that does not load particularly fast. Some browsers won't draw the page unless the ads load, making the website appear slower than it actually is - is there any way to prevent this? As in mark the script as non-essential or do some javascript trick to only draw it once it's loaded? I tried googling a solution, but to no avail.
Also, some ads are added to the site as iframe, some as JS script (much like adsense)
If loading the ads is optional, what you could do is wait to load them and then use ajax to load/add them later with jquery.
The best thing to do here is defer the loading of your ads, and anything else non-essential, until after the page has finished loading.
Attach code to load these to window.onload. That event fires when everything on the page is done loading. You can even defer loading the whole script by adding it to the DOM later. I use jQuery.getScript() for this, but there are other methods.
Load the ad after the DOM has been loaded. You would have your page load normally, then bind a function (JavaScript) which injects the ad(s).
There is also the defer attribute on tags, but it isn't fully cross-browser supported.
JavaScript: Defer Execution
You could try to put your script tags at the bottom of the page, before the closing body tag. http://developer.yahoo.com/blogs/ydn/high-performance-sites-rule-6-move-scripts-bottom-7200.html
Or you could try to load them asynchronously.
In HTML5 (not as much browser support)
<script async src="http://your.com/script.js"></script>
Another way (works with more browsers)
<script>
var resource = document.createElement('script');
resource.src = "//your.com/script.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(resource, script);
</script>
http://css-tricks.com/thinking-async/

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.

I have JavaScript code at the bottom of the page but images still load after?

I'm referencing my JavaScript files before the closing body tag, hoping they will be parsed last (as they're not needed until last). However when I analyse activity with PageSpeed in Firebug, the images seem to be requested last.
How can I make the images higher priority than the JavaScript code?
When you execute your javascript commands in the onLoad-Event the images should be read first. After the page is fully loaded the onLoad-Event is executed.
Yes, document.ready is before images. If you want it to run after images are loaded you need to use
$(window).ready(function() {});
Load your images outside of the $.ready() function

Move jQuery to the end of body tag?

My friend read an article which mentioned that moving all JavaScript files to the end of the closing body tag (</body>), will improve the performance of a web page.
I have moved all JS files to the end except the JQuery and the JS files which are attaching event to an element on page, like below;
$(document).ready(function(){
//submit data
$("#create_video").click(function(){ //... });
});
but he's saying to move the jQuery library file to the end of body tag.
I don't think it is possible, because I am attaching many events to page elements on load using jQuery selectors, and to use jQuery selectors it is must to load jQuery library first.
Is it possible to move JQuery library file to the end of page right before closing body tag (</body>) ??
Thanks
It's standard practice to move all your js includes to the bottom of your page. This is because when a browser loads script, it does not spawn a new thread to do so, so basically the browser will wait until it has loaded the script before it proceeds to the next line.
What this means for your users is that they will see a blank screen. Much better to have them see the full(ish) page as then it doesn't look like it has stalled.
The $(document).ready function says not to run until the DOM has finished being instantiated - so moving it to after body is okay so long as the JQuery library is loaded first. Unconventional and some assumptions may not be correct anymore but okay.
Just take in account that the jQuery JavaScript file must be loaded before any call to the $(...) function.
Use a "Dom Ready Queue" to collect functions to be executed once jQuery is loaded and the DOM is ready.
Example:
<html>
<head>
<script type="text/javascript">
var domReadyQueue = [];
</script>
</head>
<body>
...
<div class="foo"></div>
<script type="text/javascript">
domReadyQueue.push(function($){
$('.foo').doSomething();
})
</script>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function(){
while (domReadyQueue.length) {
domReadyQueue.shift()(jQuery);
}
});
</script>
</body>
</html>
The reason that article asked you to move scripts to the bottom, is to allow other artifacts to get downloaded first. (css & images, which will speed up apparent rendering times)
This is because HTTP 1.1 recommends only downloading 2 items per hostname. And you would definitely want your css file to be one of the first files downloaded, rather than javascript which could make the site appear to render slower (just by the fact that the browser hasn't got the css file yet and isn't sure what it should do with the html)
But if you used google to host your jQuery then that would download in parallel and negates any reason for moving it to the bottom of your pages.
Alternatively, you could set up a second hostname to host static content (such as css/scripts/images).
But google have already done the hard work for you, so it makes sense to use it if it suits. :-)
Q - Why do I often see JavaScript
written/included before the closing
body element in an (x)HTML document?
A - DOM elements can not be accessed
by JavaScript until the browser has
loaded the HTML elements into the DOM.
By placing JavaScript at the end of an
(x)HTML document (before the closing
body element), you will ensure that
the script is called as soon as the
DOM is constructed/loaded and ready
for manipulation. An advantage of this
approach is that JavaScript code is
executed right after the DOM is
constructed and possibly before the
onload event would fire.
JavaScript beginners get tripped up by
this constantly by placing code that
manipulates the DOM in the header
element of an (x)HTML document. This
causes an error because the DOM has
not yet been constructed and thus is
not yet accessible to JavaScript that
traverses/manipulates the DOM.
From JavaScript Execution & Onload Techniques in Web Browsers
Use unobtrusive javascript (adding event listeners to elements instead of onclik ="..." etc).
Put all your .js files at the bottom of the body tag, with the main library (jQuery in this case) placed first, and everything will be fine. You can use a bundler like bundle fu
You will see a big performance boost of loading your page.

Categories

Resources