Javascript Start setinterval after page loads [duplicate] - javascript

This question already has answers here:
How to make JavaScript execute after page load?
(25 answers)
Closed 7 years ago.
I have a script which displays seconds before showing hiding the div.
var seconds_left = 20;
var interval = setInterval(function() {
document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
if (seconds_left <= 0)
{
//alert('The video is ready to play.');
$('#def').fadeOut('slow');
clearInterval(interval);
}
}, 1000);
The problem is.. even the page is not fully loaded, the counting automatically starts.
What can i do to make the counting start after the page fully loaded?

You shouldn't directly assign your onload, it will replace any existing onload. Onload is used frequently so overriding it is a bad idea. Do something like this:
window.addEventListener ?
window.addEventListener("load",yourFunction,false) :
window.attachEvent && window.attachEvent("onload",yourFunction);
If you can use a JS library like jQuery it will probably make things easier for you. You can use
$(document).ready(function() {
// your code
});
Ref: https://ckon.wordpress.com/2008/07/25/stop-using-windowonload-in-javascript/

you can set an 'onload' event on your body tag, which runs as soon as your content finishes loading:
<body onload='yourFunction()'>

Try calling it in the window.onload = function () { alert("It's loaded!") }
Example
window.onload = function () {
someFunction();
}
function someFunction() {
var seconds_left = 20;
var interval = setInterval(function () {
document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
if (seconds_left <= 0) {
//alert('The video is ready to play.');
$('#def').fadeOut('slow');
clearInterval(interval);
}
}, 1000);
}

Here is the best way if you really want to make sure your page is fully loaded:
$(function() {
// work when all HTML loaded except images and DOM is ready
});
$(window).load(function() {
// this is come when complete page is fully loaded, including all
// frames, objects and images **/
});
Use the load function for this problem I suggest you. Have a good day

If you use jQuery do like this:
$(function(){
//your code
});
And it's code will run after when page is loaded.

Related

Loading External JS Files After Mouse Move or 5 Seconds Later for Better Page Speed Optimization

I am using smartsupp live chat script for my website. It is good however it dramatically increases my page loading time.
According to gtmetrix.com, my normal page load details:
Fully Loaded Time
2.6s
Total Page Size
751KB
Requests
42
But when I add this script:
Fully Loaded Time
20.6s
Total Page Size
2.00MB
Requests
66
So, I want to use this script but I don't want to load it firstly. I want to load it when visitors mouse move or 3-5 seconds later.
Do you have any solution for this? Thank you.
Default smartsupp codes like this:
<!-- Smartsupp Live Chat script -->
<script type="text/javascript">
var _smartsupp = _smartsupp || {};
_smartsupp.key = 'mykeynumber';
window.smartsupp||(function(d) {
var s,c,o=smartsupp=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;c.defer=true;
c.src='//www.smartsuppchat.com/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
</script>
EDIT:
I think this is not related with my question but I think this is another side of this problem too. According to gtmetrix.com I have "Leverage browser caching" problem beacuse of this script too. They said:
Leverage browser caching for the following cacheable resources:
https://s2.smartlook.com/rec/check (expiration not specified)
https://s2.smartlook.com/rec/init (expiration not specified)
https://s2.smartlook.com/rec/tag (expiration not specified)
https://static.smartsupp.co/chats/112939/avatar-gasqccul5z.png (expiration not specified)
https://rec-src.smartlook.com/recorder.js (5 minutes)
https://www.google-analytics.com/analytics.js (2 hours)
Maybe you can find a good solution for all of these problems. Thank you very much again.
Unfortunately other solutions are not fit for my problem. So I found a code like this:
<script>
window.onload = function(){
setTimeout(loadAfterTime, 5000)
};
function loadAfterTime() {
// your code here
}
</script>
And used it like:
<script>
var _smartsupp = _smartsupp || {};
_smartsupp.key = 'mykeynumber';
window.onload = function(){
setTimeout(loadAfterTime, 5000)
};
function loadAfterTime() {
window.smartsupp||(function(d) {
var s,c,o=smartsupp=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;
c.src='//www.smartsuppchat.com/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
}
</script>
After that, gtmetrix.com results:
Fully Loaded Time
2.7s
Total Page Size
650KB
Requests
34
So, it works! I recommend this solutions for all webmasters.
You can use javascript onload native method or document.ready from jquery library.
It is hard to accept that those loading time will be same or more or less same all the time, since it depends on internet speed and server capability.Instead of depending on setTimeout you can rely on window.onload
window.onload fires when the resource has loaded.
window.onload = function() {
// script for Smartsupp Live Chat
};
Its easy to do achieve this with jQuery. You just need to get the external js file after the document is ready and apply a set timeout function for your external script.
<script>
$(document).ready(function() {
setTimeout(function() {
var _smartsupp = _smartsupp || {};
_smartsupp.key = 'mykeynumber';
window.smartsupp || (function(d) {
var s, c, o = smartsupp = function() {
o._.push(arguments)
};
o._ = [];
s = d.getElementsByTagName('script')[0];
c = d.createElement('script');
c.type = 'text/javascript';
c.charset = 'utf-8';
c.async = true;
c.defer = true;
c.src = '//www.smartsuppchat.com/loader.js?';
s.parentNode.insertBefore(c, s);
})(document);
console.log("External js file loaded");
}, 5 * 1000) //calls the external chat after 5 seconds
});
</script>
Edit #1
Leverage browser caching doesn't works on external resources :)

How to load page only once

Below is my code but page load continuously,i want to load only once
window.onload = function () {
window.location.reload();
}
There are a few ways you could solve this, all of which require saving state across page loads. You could use cookies, localStorage, the location object itself, etc.
Here's a way that checks to see if there is a hash string 'reloaded' and, if not, adds it and reloads the page. Then, when it tries to execute again, the hash will be there and it will not reload:
if (location.hash.indexOf('reloaded') === -1) {
location.hash += 'reloaded';
location.reload();
}
$(document).ready(function(){
if(document.URL.indexOf("#")==-1){ //Check if the current URL contains '#'
url = document.URL+"#"; // use "#". Add hash to URL
location = "#";
location.reload(true); //Reload the page
}
});
Due to the if condition page will reload only once.
The other way to achieve this is :
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
window.onload = function ()
{
// for getting params value
function parse(val)
{
var result = "not found";
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
});
return result;
}
if(parse("load")!="once")
{
//sending parameter so next time it won't reload..
window.location.href += "?load=once";
window.location.reload();
}
}
By nature of visiting a page, It will only load once. You could change your code to prove this fact:
window.onload = function () {
alert("Loaded");
}
But, I would suggest the vapor.js route to detecting page load, that is, omit this onload call, because the lines of code in the onload function run after the page is loaded. I think you either don't know what your goal is or you have an entirely different problem you are trying to solve in a way that does not make sense
You built a loop,
site is loading
window.onload is triggered
reload is initiaded
site is (re-)loading
window.onload is triggered
reload is initiaded
.......
.......
Important fact for you to learn is that browsers run through your code from top to bottom and when you reload your page, the whole prozess repeats.
So every Time you reload, the window.onload event-listener is registered and calls the function attached to it, as soon as the window object is fully loaded.
There is no mechanism that tells the browser to stop.
if you would like run your Javascript code once the DOM is loaded, and you are looking for an browser independent solution i would recommend jQuery and its $( document ).ready() function.
with jQuery included to your Page:
$( document ).ready(function(){
//Code inside this function runs after your document is loaded
})

jquery auto refresh not working?

Here is a script I wrote so i could refresh a div with content every 5 seconds but for some reason it doesnt work ... I wanted it to load it with the page then start the refresh I didn't want it to have to wait for the refresh to show up.
<script type="text/javascript">
function page_load(){
$('#contentforads').load('<?php print $actual_link ?>/ads.php').fadeIn("slow");
}
function refresh(){
page_load();
var auto_refresh = setInterval(page_load,5000);
}
</script>
page_load() doesn't return a function, therefore you should pass it by reference to the interval rather than executing it.
var auto_refresh = setInterval(page_load,5000);
Don't forget to execute refresh to begin the interval.
function page_load(){
$('#contentforads').load('<?php print $actual_link ?>/ads.php').fadeIn("slow");
}
function refresh(){
page_load();
var auto_refresh = setInterval(page_load,5000);
}
refresh();
Change:
setInterval(page_load(),5000);
to:
setInterval(page_load,5000);
I'd change your code to this:
var a = function page_load(){
$('#contentforads').append(new Date());
}
setInterval(a, 5000); //every 5 seconds
Heres why I recommend:
Less code xD
Functions take up memory as they are considered variables in JS so this is more optimized
Note: Working fiddle

Javascript bookmarklet/iFrame to auto-refresh loaded page if no activity detected within set timeframe?

I have a browser-based application that I use at work (as effectively all corporate apps are now browser-based for obvious reasons) that has an annoyingly short session timeout. I'm not sure precisely what the session timeout is set to, but it's something along the order of 5-10 minutes.
Inevitably whenever I have to use it the session has timed out, I enter the information into the app, submit it, and then the page loads with a brand new session without any of the information actually being passed on - all I get is a new session. I then have to re-enter the information and submit it again in order to have it actually pull up what I want. Of course, I could first refresh the page and then enter the info, but I never know if the session is timed out or not and occasionally it runs painfully slowly so this is a waste of time. Our development team's inability to foresee that little things like this are not only annoying, but also end up costing us a ton of money when you consider the amount of time lost (I work for a VERY large corporation) just waiting for the blasted thing to reload and then having to re-enter the submitted information if a pre-refresh was forgotten as it usually is happens to be beyond me. At some point I'm hoping to become the liaison between the programmers and our customer service body.
Anyway, I digress.
What I'm looking to do is this: I'd like to create a Javascript bookmarklet or something that will automatically refresh whatever page it happens to be on if activity isn't detected within a certain timeframe. This timeframe will be a bit short of whatever I end up figuring out what the session timeout is. Basically I just want to make the page reload itself every, say, five minutes if there hasn't been activity within that period. (I don't want it to refresh out of the blue because the time is up while I'm in the middle of using the app, the only time it should do the auto-refresh is if the app page has been sitting idle)
Can this be done with a Javascript bookmarklet? Should I program a page "wrapper" of sorts that loads the application page within an iFrame or something of the sort? The app site that I use has many subpages, and I'd prefer for it to refresh whatever page I happen to be on at the time if the auto-refresh timeout occurs. Of course, if that isn't possible I'd accept it just reloading the main site page if that's not easily possible since if I've been out of the app long enough for the timeout to happen then I likely don't need to still be on whatever account/page I was on at the time.
Hopefully I've explained myself well enough. The logic is simple - if no activity detected withing x amount of time, refresh the current page is the gist of it.
Thank you, my StackOverflow brethren, yet again for your assistance.
-Sootah
Since I have no ability to influence the coding of the page itself, I've got to have the most simple solution possible. A bookmarklet that times the last refresh/pageload and then refreshes the same page if the timeout is reached would be perfect.
If that's not possible, then if I could write a simple page that I could run from the local computer that'd do the same function by loading the page in a frame or something that'd also be acceptable.
EDIT 10/3/11 7:25am MST
Since I work graves and an odd schedule at work (and this site, unfortunately, being blocked there since it's considered a 'forum' - I work in finance, they're overly cautious about information leakage) before I award the bounty, does one of these event detectors detect the last time the page loaded/? Something like document.onload or whatnot. I'm thinking that setting the timer from the last time the page was loaded is going to be the simplest and most effective approach. My mouse may move over the browser that I have the site open in inadvertently while working on other things, and if the timer resets because of that without me actually having interacted with the site in such a way that a page loads/reloads then the session times out.
This is the bookmarklet code #1 for you, set up to FIVE seconds. Change time to what you like more.
javascript:
(function () {
var q = null;
function refresh() { window.location.reload(); }
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
document.body.onclick = x;
document.body.onmousemove = x;
document.body.onmousedown = x;
document.body.onkeydown = x;
}())
p.s.: would have been nicer to include eventListeners, but i suppose you need to support IE8, too, so i replaced them with inline events, - if you DON'T need IE8, use code #2:
javascript:
(function () {
var q = null;
function refresh() { window.location.reload(); }
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
document.body.addEventListener( "click", x, false );
document.body.addEventListener( "mousemove", x, false );
document.body.addEventListener( "mousedown", x, false );
document.body.addEventListener( "keydown", x, false );
}())
edit: in response to comments, here is code #3 with pulling, instead of refreshing page. Yet, despite advices to use iframe, i decided it might be desirable to not execute scripts on that page, so we will use img instead:
javascript:
(function () {
var q = null;
var u = window.location.href;
var i = document.createElement('img');
i.style = "width: 1px; height: 1px;";
document.body.appendChild(i);
function refresh() {
i.src = "";
i.src = u;
x();
}
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
var evs = ['click', 'mousemove', 'mousedown', 'keydown'];
for( var j = 0; j < evs.length; j++) {
document.body['on'+evs[j]] = x;
}
}())
Create a bookmark and place the code below in the "url" value. Please note that you should change the values of "sessiontimeout" and "checkinterval". They're both in milliseconds.
javascript:(function(){var lastmove = new Date().valueOf(),sessiontimeout=10000,checkinterval=1000;document.onmousemove = function(e){lastmove= new Date().valueOf();};timer = setInterval( function() {var differential = (new Date().valueOf() - lastmove);if (differential > sessiontimeout) {var iframe = document.getElementById("bkmrkiframerefresher");if (iframe) { document.getElementsByTagName("body")[0].removeChild(iframe);} iframe = document.createElement("iframe");iframe.setAttribute("src", "/");iframe.setAttribute("width", 0);iframe.setAttribute("height", 0);iframe.setAttribute("style", "width:0;height:0;display:none;");iframe.setAttribute("id", "bkmrkiframerefresher");document.getElementsByTagName("body")[0].appendChild(iframe);lastmove = new Date().valueOf();} }, checkinterval);})();
This is a bookmarklet that will inject the code below in the page. I tested the bookmarklet in Chrome. It worked on multiple sites except stackoverflow, it seems that they block framing for security reasons. Before you leave your desk, open the website which session you wanna keep alive, then click the bookmarklet on it. Once you're back, refresh the page in order to get rid of the running timers.
The formatted (and commented) code is:
<script type="text/javascript">
// last time the mouse moved
var lastmove = new Date().valueOf();
var sessiontimeout=10000;
var checkinterval=1000;
// reset the last time the mouse moved
document.onmousemove = function(e){
lastmove= new Date().valueOf();
}
// check periodically for timeout
timer = setInterval( function() {
var differential = (new Date().valueOf() - lastmove);
if (differential > sessiontimeout) {
var iframe = document.getElementById("bkmrkiframerefresher");
// iframe already exists, remove it before loading it back
if (iframe) {
document.getElementsByTagName("body")[0].removeChild(iframe);
}
// alert("more than 10 secs elapsed " + differential);
// create an iframe and set its src to the website's root
iframe = document.createElement("iframe");
iframe.setAttribute("src", "/");
iframe.setAttribute("width", 0);
iframe.setAttribute("height", 0);
iframe.setAttribute("id", "bkmrkiframerefresher");
iframe.setAttribute("style", "width:0;height:0;display:none;");
document.getElementsByTagName("body")[0].appendChild(iframe);
// reset counter.
lastmove = new Date().valueOf();
}
}, checkinterval);
</script>
Stefan suggested above that you need no logic besides polling. The edited code is the following:
<script type="text/javascript">
var pollInterval=1000;
timer = setInterval( function() {
var iframe = document.getElementById("bkmrkiframerefresher");
// iframe already exists, remove it before loading it back
if (iframe) {
document.getElementsByTagName("body")[0].removeChild(iframe);
}
// create an iframe and set its src to the website's root
iframe = document.createElement("iframe");
iframe.setAttribute("src", "/");
iframe.setAttribute("width", 0);
iframe.setAttribute("height", 0);
iframe.setAttribute("id", "bkmrkiframerefresher");
iframe.setAttribute("style", "width:0;height:0;display:none;");
document.getElementsByTagName("body")[0].appendChild(iframe);
}
}, pollInterval);
</script>
This code only reload the page once
Here is a bookmarklet(inspired by Kaj Toet's pseudo code), tested in Chrome and Safari, change the timeout value with the var time at the start of the line
Onliner:
javascript:var time = 500; var timeoutFunc = function(){location.reload(true);};timeout = setTimeout(timeoutFunc,time);document.onmousemove = function() {clearTimeout(timeout);timeout = setTimeout(timeoutFunc,time); };
Code
//The time in milliseconds before reload
var time = 500;
//The function that is called when the timer has reached 0
var timeoutFunc = function() {
location.reload(true);
};
//start the timer
timeout = setTimeout(timeoutFunc,time);
//restart the timer if the mouse is moved
document.onmousemove = function() {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunc,time);
};
pseudocode
timeout = settimeout("call",200);
document.onmousemove = function() { timeout = new timeout("call",200); }
function call() {
document.refresh();
}
like this?

Loading message

Searching for a js script, which will show some message (something like "Loading, please wait") until the page loads all images.
Important - it mustn't use any js framework (jquery, mootools, etc), must be an ordinary js script.
Message must disappear when the page is loaded.
Yeah an old-school question!
This goes back to those days when we used to preload images...
Anyway, here's some code. The magic is the "complete" property on the document.images collection (Image objects).
// setup a timer, adjust the 200 to some other milliseconds if desired
var _timer = setInterval("imgloaded()",200);
function imgloaded() {
// assume they're all loaded
var loaded = true;
// test all images for "complete" property
for(var i = 0, len = document.images.length; i < len; i++) {
if(!document.images[i].complete) { loaded = false; break; }
}
// if loaded is still true, change the HTML
if(loaded) {
document.getElementById("msg").innerHTML = "Done.";
// clear the timer
clearInterval(_timer);
}
};
Of course, this assumes you have some DIV thrown in somewhere:
<div id="msg">Loading...</div>
Just add a static <div> to the page, informing user that the page is loading. Then add window.onload handler and remove the div.
BTW, what’s the reason of this? Don’t users already have page load indicators in their browsers?
You should do async ajax requests for the images and add a call back when it's finished.
Here's some code to illustrate it:
var R = new XMLHttpRequest();
R.onreadystatechange = function() {
if (R.readyState == 4) {
// Do something with R.responseXML/Text ...
stopWaiting();
}
};
Theoretically you could have an onload event on every image object that runs a function that checks if all images is loaded. This way you don´t need a setTimeOut(). This would however fail if an image didn´t load so you would have to take onerror into account also.

Categories

Resources