I want to execute some part of my addon code on page load, so I'm looking for page load event in browsers.
if (window.addEventListener)
window.addEventListener("load", func, false);
else if (window.attachEvent)
window.attachEvent("onload", func);
function func() {
alert("page loaded");
//my code here
}
In Firefox I'm able to catch load event, but in IE9 I'm unable to get this. Alternately, using jQuery call:
$(document).ready(function(){
//my code here
});
we can get this, but I need this functionality without using jQuery.
This will execute in IE9:
window.onload = func;
To modify your code:
if (window.addEventListener) {
window.addEventListener("load", func, false);
} else if (window.attachEvent) {
window.attachEvent("onload", func);
} else {
window['onload'] = func;
}
The more general event handler attachment would be:
function Subscribe(event, element, func) {
if (element.addEventListener) {
element.addEventListener(event, func, false);
} else if (element.attachEvent) {
element.attachEvent("on" + event, func);
} else {
element['on' + event] = func;
}
}
Subscribe('load', window, func);
maybe you can try this
window.onload = function () {
// do something here
};
Related
I would like to stop some script working on window resize and replacing it by mine.
The problem is I can't get name of function from script mentioned above. So is there some way to remove all of that WITHOUT USING JQUERY ON IE8? (event listeners does not work).
Here is the full answer with a support for IE < 9:
https://stackoverflow.com/a/13651455/3774114
window.attachEvent('onresize', function() {
alert('attachEvent - resize');
});
}
else if(window.addEventListener) {
window.addEventListener('resize', function() {
console.log('addEventListener - resize');
}, true);
}
else {
//The browser does not support Javascript event binding
}
Similarly, you can remove events in the same way
if(window.detachEvent) {
window.detachEvent('onresize', theFunction);
}
else if(window.removeEventListener) {
window.removeEventListener('resize', theFunction);
}
else {
//The browser does not support Javascript event binding
}
Just override it:
window.onresize = function () {
// your code
};
Edit:
I suppose the issue is linked to IE version...
Try that :
window.addEventListener("resize", function (e) {
e.stopPropagation();
// your code
});
Update
See for IE8 :
window.attachEvent("resize", function (e) {
e.stopPropagation();
// your code
});
Now for whatever reason the original author does something on initialization I can't quite make sense of. There is this code which seems to me to be redundant:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, false);
}
(function() {
/*#cc_on
try {
document.body.doScroll('up');
return init();
} catch(e) {}
/*#if (false) #*/
if (/loaded|complete/.test(document.readyState)) return init();
/*#end #*/
if (!init.done) setTimeout(arguments.callee, 30);
})();
if (window.addEventListener) {
window.addEventListener('load', init, false);
} else if (window.attachEvent) {
window.attachEvent('onload', init);
}
function init()
{
if (arguments.callee.done) return;
arguments.callee.done = true;
// do your thing
//[...]
}
What might the purpose of this be? Or is it nonsense?
The code is making sure that init() function gets called.
It's binding the init function to event listeners that fire when the DOM or page have been loaded.
If those events have already been fired determined by the readyState then it's calling init directly, otherwise it keeps checking every 30 milliseconds for the readyState.
// Call init function when DOM is loaded
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, false);
}
// Immediately invoked function expression that calls init
// function if doScroll method does not throw error.
(function() {
try {
document.body.doScroll('up');
return init();
} catch(e) {}
// Call init function if DOMContentLoaded event has already been
// fired or if page is already loaded.
if (/loaded|complete/.test(document.readyState)) return init();
// arguments.callee is a reference to it's executing function
// which is this immediately invoked function expression.
// It will keep calling it every 30 milliseconds while init
// has not been called yet.
if (!init.done) setTimeout(arguments.callee, 30);
})();
// Call init function when window is loaded.
// `load` event is fired after DOMContentReady, when
// everything has loaded in the page.
if (window.addEventListener) {
window.addEventListener('load', init, false);
// Same as above but for IE versions 8 or less
} else if (window.attachEvent) {
window.attachEvent('onload', init);
}
function init() {
// If init has been called then immediately return.
if (arguments.callee.done) return;
// Set flag on itself to indicate that it init been called.
arguments.callee.done = true;
// do your thing
//[...]
}
I have the following code which when embedded within a loaded html page works successfully:
<HEAD>
<script language="javascript" type="text/javascript">
document.addEventListener('DOMContentLoaded', function ()
{
document.documentElement.addEventListener("touchstart", function (e)
{
if (['A', 'BUTTON'].indexOf(e.target.tagName) === -1)
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC("ontouchstart:");
}
else
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC(e.target);
}
}, true);
}, false);
function invokeObjectiveC(action) {
...
}
However if I take it out of the html and try to load it separatly then it is not working.
When loading it separately it looks like this:
alert('test');
function addListener()
{
alert('adding listener');
document.addEventListener('DOMContentLoaded', function ()
{
document.documentElement.addEventListener("touchstart", function (e)
{
alert('touchstart');
if (['A', 'BUTTON'].indexOf(e.target.tagName) === -1)
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC("ontouchstart:");
}
else
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC(e.target);
}
}, true);
}, false);
}
addListener();
function invokeObjectiveC(action) {
...
}
When added, a "test" and an "adding listener" alert dialog are displayed so I know this part is working.
However the code then doesn't work - its supposed to detect touches (this is on iOS) in certain parts of the screen.
With the code within the html everything works fine and it executes when the screen is touched, when its loaded separatly nothing happens when the screen is touched.
Any ideas what the problem could be?
====== UPDATE
I tried running the following during various stages of the lifecycle, including before the request to even load the page has been issued, but 'Dom content loaded' never appears:
var script = document.createElement('script');
script.type = 'text/javascript';
script.text =
var Test =
{
f: function()
{
if (!event.originalTarget.defaultView.frameElement)
{
alert('DOM content loaded');
}
}
}
function addTestListener()
{
alert('adding listener');
window.addEventListener("DOMContentLoaded", function(e) { Test.f(); }, false);
}
document.getElementsByTagName('head')[0].appendChild(script);
From your comment about the iOS function, I suspect that the document is already loaded when you try to execute your javascript. If that's the case, then the DOMContentLoaded event has already happened so you code will never be initialized. You can fix that by checking to see if the document is already loaded by changing your code to this:
function addListener() {
alert('adding listener');
function init() {
document.documentElement.addEventListener("touchstart", function (e) {
alert('touchstart');
if (['A', 'BUTTON'].indexOf(e.target.tagName) === -1) {
e.preventDefault();
e.stopPropagation();
invokeObjectiveC("ims-ontouchstart:");
} else {
e.preventDefault();
e.stopPropagation();
invokeObjectiveC(e.target);
}
}, true);
}
if (document.readyState === "complete") {
init();
} else {
document.addEventListener('DOMContentLoaded', init, false);
}
}
addListener();
function invokeObjectiveC(action) {
...
}
I changed the line
function addListener()
into
window.onload = function addListener()
and it seems to have done the trick
I'm using the popular addLoadEvent as follows for all my JS loading:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent( locationToggle );
addLoadEvent( step1 );
addLoadEvent( step2 );
addLoadEvent( step3 );
addLoadEvent( getCounties );
addLoadEvent( mapSelection);
Everything I've read suggests this is a fairly bullet proof way of avoiding onload conflicts. And yet this method doesn't appear to working any better than wrapping the functions in an anonymous window.onload function. Both methods are causing identical onload conflicts with this set of functions.
I am loading these functions from within the same file as the addLoadEvent function itself. I'm also using calender.js which is a third party file which uses mootools 1.2.4 in an additional file. My files are otherwise free of Javascript.
First, could someone verify I've not damaged the code and I'm using it right. Second could someone suggest why the above is not resolving the conflicts?
edit
The problem persists with all other Javascript files disabled.
Your code is fine. The problem is that setting event handlers in the DOM 0 way doesn't ensure that they won't replaced by other code.
You may try the new W3C standard addEventListener and the IE version attachEvent, because the handlers you attach by them cannot be replaced by 3rd party code.
// window.onload W3C cross-browser with a fallback
function addLoadEvent(func) {
if (window.addEventListener)
window.addEventListener("load", func, false);
else if (window.attachEvent)
window.attachEvent("onload", func);
else { // fallback
var old = window.onload;
window.onload = function() {
if (old) old();
func();
};
}
}
Note, that IE will execute the function in reversed order not in the order you added them (if this is a concern).
Finally, I don't know when you want to run your code, but if you don't want to wait for images to load you can execute your functions earlier then window.onload.
Dean Edwards has a nice script which will let you to do that.
With this you can attach your functions for an earlier event: document.ready (DOMContentLoaded)
// document.ready
function addLoadEvent(func) {
if (typeof func == "function") {
addLoadEvent.queue.push(func);
}
}
addLoadEvent.queue = [];
//////////////////////////////////////////////////////////////////////////////
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff: execute the queue
var que = addLoadEvent.queue;
var len = que.length;
for(var i = 0; i < len; i++) {
if (typeof que[i] == "function") {
que[i]();
}
}
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)>"
+"<\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
Note: the usage is the same for both methods as it was for your version.
I have a Flash movie embedded with swfobject in a html container.
Through ExternalInterface I have registered a Javascript function to fire callback to my flash app.
ExternalInterface.addCallback("notifyClose", notifyOnClose );
The Javascript function is added as an event listener to fire onbeforeunload.
<script language="JavaScript">
function getSWF(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1){
return window[movieName];
}else { return document[movieName];}
}
var bye = function() {
getSWF('flashContainer').notifyClose('> WE ARE CLOSING APP!');
//alert('WE ARE CLOSING APP!.');
};
var hola = function(){
getSWF('flashContainer').notifyClose('> WE ARE opening APP!');
alert('WE ARE opening APP!.');
};
if(window.addEventListener) {
window.addEventListener('load', hola,false);
window.addEventListener('beforeunload', bye, false);
} else if (window.attachEvent) {
window.attachEvent('onload', hola);
window.attachEvent('onbeforeunload', bye);
}
</script>
I have tested in Firefox and IE. Firefox works as expected but not in IE.
In IE I get notified in Flash with the onload message, but not onbeforeunload.
Is it some kind of sandbox restriction? Just bad code?
The problem is the "on" in your code below in the attachEvent().
if(window.addEventListener) {
window.addEventListener('load', hola,false);
window.addEventListener('beforeunload', bye, false);
} else if (window.attachEvent) {
window.attachEvent('onload', hola);
window.attachEvent('onbeforeunload', bye);
}
Try something like the code below for your Event Listener code and see the following link for more information: http://bytes.com/topic/javascript/answers/147027-addeventlistener-function-ie
//*** This code is copyright 2003 by Gavin Kistner, !#phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//*** Reuse or modification is free provided you abide by the terms of that license.
//*** (Including the first two lines above in your source code satisfies the conditions.)
//***Cross browser attach event function. For 'evt' pass a string value with the leading "on" omitted
//***e.g. AttachEvent(window,'load',MyFunctionNameWithoutParenthesis,false);
function AttachEvent(obj,evt,fnc,useCapture){
if (!useCapture) useCapture=false;
if (obj.addEventListener){
obj.addEventListener(evt,fnc,useCapture);
return true;
} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
else{
MyAttachEvent(obj,evt,fnc);
obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
}
}
//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
if (!obj.myEvents) obj.myEvents={};
if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
var evts = obj.myEvents[evt];
evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
var evts = obj.myEvents[evt];
for (var i=0,len=evts.length;i<len;i++) evts[i]();
}