window.onload executing before the web is loaded - javascript

Im using this code to fire a function right after the page is loaded:
function loadpapi(){
alert("Hello World!");
}
function pctaddLoadEvent(func) {
var oldonload = document.onload;
if (typeof document.onload != 'function') {
document.onload = func;
} else {
document.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
pctaddLoadEvent(loadpapi());
But is starting before the page loads, you can try it here: http://jsfiddle.net/KuTxh/

pctaddLoadEvent(loadpapi());
This code calls loadpapi (just like any other function call) and passes the result to pctaddLoadEvent.
You want to pass the function without calling it.

I changed the event from document.onload to window.onload: see a discussion here.
This document.onload vs window.onload is a complicated subject. It is likely the document.onload event isn't fired by your browser at all. (Or, as one deals with the window and the other with DOM tree, it is possible that the document.onload event has already fired when your javascript function took action - more testing can confirm that.)
Also, the function passed as parameter goes without the (), as you want to pass the function itself, not its returning value.
function loadpapi(){
alert("Hello World!");
}
function pctaddLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
pctaddLoadEvent(loadpapi);
Check demo fiddle: http://jsfiddle.net/st4kQ/

Related

Call window.onload function in code behind not working

I have written a js function in aspx like below
window.onload = function () {
document.getElementById('grid-overlay').style.display = 'block';
}
Now I want to call this function in code behind. I tried like below:-
if (dtmkey.Rows.Count > 0)
{
HidMode.Value = "M";
HidMKey.Value = dtmkey.Rows[0]["mkey"].ToString();
var scriptSource = "function onload() { alert(""); };\n";
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "HelpScript", scriptSource, true); // Not working
}
kindly suggest what is wrong
window.onload is an event handler for the load event of a window & the attached function is function that will be called on load event.
Also it is not clear what you are trying to do at this point
// I ran this variable in console, it threw unexpected syntax
var scriptSource = "function onload() { alert(""); };\n"; //
Are you trying to call a function expression here?
you can make this changes and test it
function onload(){ // This is a function expression and onload not same as window.onload
document.getElementById('grid-overlay').style.display = 'block';
}
window.onload = function () {
onload() // call onload function here once window has finished loading
}
If you are looking for onload here you can replace the below snippet
var scriptSource = "function onload() { alert(""); };\n"; with `onload();`

google analytics stopped tracking

i've been fighting with this problem from a while now. I think it all started when i've added my website to google webmaster's tool: at some point I started receiving an alert saying my website was missing the tracking code, but actually it was there, and even though it said it was missing, i still got my analytics stats.
at that time, the code was include in a .js file containing all of my javascript. it was included right before the </body> tag and it was loaded this way:
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "js/build/production.min.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else
window.onload = downloadJSAtOnload;
</script>
</body>
i've found this script on some blog (http://www.giftofspeed.com/defer-javascripts/) and I use this to defer javascript loading to make the page to load faster.
at some point i thought deferring the ga code was the problem (as it's all in that production.min.js file) so i've moved the ga code outside of that. and now it's like this
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "js/build/production.min.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else
window.onload = downloadJSAtOnload;
</script>
<script>
//my google analytics code here
</script>
</body>
once I did this, the alert got solved BUT the tracking is not happening anymore.
I've been using GA from ages and I never had problems like these. What could this be? I feel like i've tried it all.
Approach for modern browsers
https://github.com/jfriend00/docReady/blob/master/docready.js
Your customisation:
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "js/build/production.min.js";
document.body.appendChild(element);
}
(function(funcName, baseObj) {
"use strict";
// The public function name defaults to window.docReady
// but you can modify the last line of this function to pass in a different object or method name
// if you want to put them in a different namespace and those will be used instead of
// window.docReady(...)
funcName = funcName || "docReady";
baseObj = baseObj || window;
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
// call this when the document is ready
// this function protects itself against being called more than once
function ready() {
if (!readyFired) {
// this must be set to true before we start calling callbacks
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
// if a callback here happens to add new ready handlers,
// the docReady() function will see that it already fired
// and will schedule the callback to run right after
// this event loop finishes so all handlers will still execute
// in order and no new ones will be added to the readyList
// while we are processing the list
readyList[i].fn.call(window, readyList[i].ctx);
}
// allow any closures held by these functions to free
readyList = [];
}
}
function readyStateChange() {
if ( document.readyState === "complete" ) {
ready();
}
}
// This is the one public interface
// docReady(fn, context);
// the context argument is optional - if present, it will be passed
// as an argument to the callback
baseObj[funcName] = function(callback, context) {
// if ready has already fired, then just schedule the callback
// to fire asynchronously, but right away
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
// add the function and context to the list
readyList.push({fn: callback, ctx: context});
}
// if document already ready to go, schedule the ready function to run
// IE only safe when readyState is "complete", others safe when readyState is "interactive"
if (document.readyState === "complete" || (!document.attachEvent && document.readyState === "interactive")) {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
// otherwise if we don't have event handlers installed, install them
if (document.addEventListener) {
// first choice is DOMContentLoaded event
document.addEventListener("DOMContentLoaded", ready, false);
// backup is window load event
window.addEventListener("load", ready, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
})("downloadJSAtOnload", window);
// modify this previous line to pass in your own method name
// and object for the method to be attached to
</script>

External JavaScript with jQuery dependence being loaded before jQuery

Externally loading a script, but my script was placed by the client above jQuery (which is a requirement), as such, my script does not work.
I am trying to make my code wait until jQuery has loaded before executing, but I am having difficulty with nested functions within my code; specifically $(x).hover, or $(x).click etc.
I can separate my functions without much trouble, which include jQuery selectors (but they won't be called unless 'x y or z' is done (i.e. until after jQuery is loaded).
I don't know how to have the hover, click etc implemented as they don't work within my $(document).ready(function(){... which is located within the onload yourFunctionName described below - with thanks to user #chaos
Link to onload hook: https://stackoverflow.com/a/807997/1173155
and a quote of the above link:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
yourFunctionName();
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Thanks in advance for any help with this.
I have also looked into a loop that checks if jQuery is activated before continueing, but did not implement it as I found that JavaScript does not have a sufficient sleep method that sleeps that specific script.
Solution:
if(typeof jQuery === "undefined"){
if(window.attachEvent) {
window.attachEvent('onload', myLoadFunction);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
myLoadFunction();
};
window.onload = newonload;
} else {
window.onload = myLoadFunction;
}
}
}
else {
myLoadFunction();
}

Waiting for .ready and button click before function

My Google map only shows if function a is document.ready. However, then the function dothis() is called before the user clicks a button which calls function getMyID(inputId).
How do I run my script when the document is ready and a button is clicked?
Here's my code:
function dothis(inputId)
{
if (inputId == "1"){
dlat=30.745271;
dlng=0.578793;
getLocation();
}
else if (inputId == "2"){
dlat=40.836671;
dlng=0.578793;
currentloc();
}
}
$(document).ready(function a() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?key=ALsbSyEQvVel4MCu9xMBvD_92qAuqrFrcnos0dc&libraries=geometry,places&sensor=true&callback=dothis';;
document.body.appendChild(script);
};
$(document).ready(function() { a(); })
Well, why not call a() like
$(document).ready(function() { a(); })
Or if you don't use jquery, then
window.onload = a();
OnLoad works a bit differently though: it doesn't wait for the resources to load (e.g. images) to fire the event. jQuery document-ready event will wait for all the resources to load and then fires the event.
If you want to use jQuery, try it this way :
function dothis() {
...
}
$(document).ready(function() {
$('#MyButton').click(dothis);
}
This way, the button will be associated to the dothis function which can be called once the document is ready ;)
what you want to do is to call window.onload and initialize you button click handler there
eg
function dothis() {
// Do this
}
function getInput(input) {
// Get input
}
function init() {
document.getElementById('mybutton').onclick = getInput
}
window.onload = init

window.onbeforeunload executed on page refresh instead of on page close

I'm using window.onbeforeunload to pop up a confirm dialog when a close event occurs, but the confirm dialog appears on page refresh and doesn't execute on page close.
Here's the JavaScript code:
<script language="JavaScript">
window.onbeforeunload = confirmWinClose();
function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}
</script>
I tried it on Chrome, Firefox and Internet Explorer.
PROBLEM WITH YOUR CODE:
the function will be called when you refresh, because on refresh the page is unloaded and then reloaded.
in your solution, you should also note that you are not assigning a function to window.onbeforeunload but you are assigning the return value of the function when you write
window.onbeforeunload = confirmWinClose();
which might also execute the function (based on where you place it in the javascript) whenever the assignment is done. For e.g.
function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}
window.onbeforeunload = confirmWinClose();
the above code will execute the confirmWinClose function whenever this js is loaded.
(not your case as you have defined the function after call, so won't be executed on load, but you should remember this)
SOLUTION:
the below solution is working for close also
instead of your solution, i tried this
JS:
window.onbeforeunload = function() {
var confirmClose = confirm('Close?');
return confirmClose;
}
or
window.onbeforeunload = confirmWinClose; //note the absence of calling parantheses
function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}
this works as expected.
also note that you should return from the onbeforeunload explicitly.
even if you have to call a function, you should do
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
No full solution, but you can intercept the F5 key (not intercepted if the user click on the refresh browser button...)
var isRefresh = false;
// with jquery
$(function() {
$(document).on("keydown", function(e) {
if (e.which === 116)
{
isRefresh = true;
}
});
});
window.onbeforeunload = function() {
if (! isRefresh)
{
return confirm ('Close ?');
}
return false;
};
Since you anyway only want to display your text, What just using the onbeforeunload as it is expected just return the string?
<script language="JavaScript">
window.onbeforeunload = confirmWinClose;
function confirmWinClose() {return "close?";}
</script>
Try this it will work. You were assigning the method to onload that need to execute when it event occur so its need to be like object. refer link for better explanation - var functionName = function() {} vs function functionName() {}
window.onbeforeunload = confirmWinClose;
function confirmWinClose () {
var confirmClose = confirm('Close?');
return confirmClose;
};

Categories