I am working on a new graph for my site, using CSS3/HTML5 (canvas tag). Everything is going great so far, but I have one problem: Right now, the canvas loads blank, and the user has to click on a link to trigger the JS that draws the graph.
Its been a while since I had JS that I wanted to run immediately, so I figured I would ask what the best way to handle this would be.
P.S. Due to compatibility issues with one of the frameworks I use, I cannot use JQuery.
An unobtrusive solution
window.onload = function() {
// ... do stuff
};
You can run JS immediately from the body element's onLoad attribute:
<body onload="myFunc();">
Related
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);
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?
Is it possible to do something after the dom is ready but it is not rendered(White screen)
I would like to hide the contents from user and after some operations i would like to show the final picture.
I could use "display:none" on my body tag but i am working on a huge project so i dont want to change every page.
Thanks
Here is how?
document.onload = function() {
//your codes
}
Unlike, window.onload this function runs after the DOM is loaded, so the manipulation is possible, but it does not require all the elements to be rendered.
Is it possible to do something after the dom is ready but it is not rendered
Browsers render the DOM incrementally as they parse the HTML into it. The state you describe will not happen naturally.
You can fake it such…
I could use "display:none" on my body tag but i am working on a huge project so i dont want to change every page.
If you don't want to change every page because it is too much work, then too bad. Go and set up an external stylesheet that every page uses.
If you don't want to change every page because you only want the changes to appear on certain pages, then use a more specific selector.
That said, preventing content from displaying and giving users a white screen (or even a loading screen) is just going to turn people off and drive lots of them to another site. I wouldn't recommend doing this.
if you could use JQuery this one is called when the dom is ready but the page not loaded
$(document).ready(function(){
)};
I'll contribute my own 2 cents here.
With jquery, the $("document").ready() event fires after the DOM has been fully loaded(without images, that is) to your browser, but not displayed. So I think to achieve what you want, you'll have to input some handler function inside the ".ready()" method to handle whatsoever you desire to achieve.
Is that what you were looking for?
Hi, my question is, is it possible to set index.html#box02 as my homepage instead of index.html?
I am building a website with panning divs.
Exactly like http://demos.flesler.com/jquery/scrollTo/
Because of the panning effect, I design the whole site on a single html file - index.html. I guess it is not the best way, but I did not wish to break the animation effect. Or is there another better way?
So what i did was to create index.html and create many divs like:
example.com/index.html (Gallery)
example.com/index.html#box01 (About Us)
example.com/index.html#box02 (Homepage)
example.com/index.html#box03 (Contact Us)
I have tried to redirect using:
.htaccess (tried typing "DirectoryIndex index.html#box02" in .htaccess but fail to work)
tried redirecting using javascript in index.html:
<script type ="text/javascript">
function init(){
location.href = "index.html#box02";
}
</script>
<body onLoad="init()">
(but there is a lag time, as it loads index.html first, then it loads index.html#02)
Is it possible to load index.html#box02 straightaway instead of index.html?)
Would like to get help from more experienced web designers here?
Everything after the # is for the browser to handle (and not the server), so changes on the server will not really make a difference. Your javascript solution is a good way to go about it.
One other way you can address this is to make the contents of example.com/index.html#box02 available at index.html itself, by perhaps rendering it on load.
Nevertheless, the lag time you mention for the javascript solution is going to be present either way, as long as javascript is rendering the panning effect (which I believe is the case). I don't think your javascript solution will add significant lag here
I have a webpage created by a php script that upon loading will contain 0 to N div elements. For each div I run a specific javascript code that manipulates data relevant to that div.
One of the things this code does is create an img element and set its 'src' attribute to a certain url of an image of a known (but variable) size. This is done for caching. Those images are not supposed to be displayed in the initial page layout - but each should appear after a certain user input (mouse hover) - so I'm trying to cache the images so it won't take long for them to appear.
The loading of the images of-course takes time - and each time an image loads the code blocks resulting in high load times. an example:
<div id="i1">
<script type="text/javascript">
/* run code relevant to 'i1', and amongst other things load some image
into a detached img element for later use. let's call this code 'bcode' */
</script>
<div id="i2">
<script type="text/javascript">
/* run 'bcode' for i2 */
</script>
<div id="...and so on">
To try having the code run asynchronously, I tried this:
<div id="i1">
(function() {
var asyncScriptElement = document.createElement('script');
asyncScriptElement.async = true;
var scriptText = document.createTextNode ('here I put all of the relevant "bcode"');
asyncScriptElement.appendChild (scriptText);
document.getElementById ('Img_1_2').appendChild (asyncScriptElement);
}());
It works under FF (still not fast enough), and it obviously doesn't work under IE.
Do you have any suggestion as to how to achieve this?
Also note, that I don't really need to get anything from another external php (i.e. to use XMLHttpRequest) - I got all the data I need in this php. I just need a way to make the loading of the images unblocking...
Looks like you need the waitfor/and construct provided by the apollo library: http://onilabs.com/stratifiedjs#waitfor-and
Javascript is single threaded and always runs synchronously.
There are browser extensions to get around this, notably the concept of Javascript Workers in Mozilla
I would wrap your scripts in an HTML page (eventually generated by PHP) and download it as an iframe to assure the same behaviour for any browser.
There are other more elegant options with pros and cons; here you can find a comparison of viable options, browser compatibility and a nice decision tree.