Here's an example for registering a function on document load (most of it taken from JavaScript: The Definitive Guide):
"use strict";
//run function f when document is loaded
function onLoad(f) {
if (onLoad.loaded) // If already loaded
window.setTimeout(f, 0);
else if (window.addEventListener)
window.addEventListener("load", f, false);
}
onLoad.loaded = false;
onLoad(function() { onLoad.loaded = true; });
onLoad(myfunc);
function myfunc() {
console.log("Hello, world!");
}
I'm getting confused with the line onLoad(function() { onLoad.loaded = true; });. I can tell that it's self-invocation, but using the function name again baffles me. Why is it needed? I find that if I do only (function() { onLoad.loaded = true; }); then also the output is the same.
Finally, I can get the same output by using:
function myfunc() {
console.log("Hello, world!");
}
window.onload = (function() {window.setTimeout(myfunc, 0);});
How is my code better/worse?
Thanks in advance!
I'm getting confused with the line onLoad(function() { onLoad.loaded = true; });. I can tell that it's self-invocation, but using the function name again baffles me.
It isn't a self-invocation.
It is a call to the function onLoad (previously defined) with one argument (which is a function expression).
Finally, I can get the same output by using… How is my code better/worse?
Your code will:
Only support a function function to be called when the load event fires. If you try to assign another function, it will overwrite the previous one instead of setting up two functions to be called when the event fires.
Won't call the function immediately (or at all) if the load event has already fired (so you can't use it in a script that can be dynamically added to the page as well as being used normally)
Related
I luckily found this code on the net for continuos add on onload from a different subject completely
function myPluginLoadEvent(func) {
// assign any pre-defined functions on 'window.onload' to a variable
var oldOnLoad = window.onload;
// if there is not any function hooked to it
if (typeof window.onload != 'function') {
// you can hook your function with it
window.onload = func
} else { // someone already hooked a function
window.onload = function () {
// call the function hooked already
oldOnLoad();
// call your awesome function
func();
}
}
}
// pass the function you want to call at 'window.onload', in the function defined above
myPluginLoadEvent(func);
However, this only allow for one add on onload call. How do I loop this for multiple on load call such as for i, 1++ ?
Many thanks in advance.
The code you posted will work repeatedly. Each time it's called, oldOnLoad contains whatever was previously assigned to window.onload, which could be the result of a previous use. So it just keeps chaining all the functions.
However, the modern approach is to use addEventListener rather than assigning to window.onload.
window.addEventListener("load", func);
I am accessing few methods written in another js file. So i'm accessing them like this:
file1:
function minit() {
this.addval = function(val1, val2) {
return val1 + val2;
}
function autoexecute(d) {
//do something here//
//raise event//
}
};
file2:
var con = new minit();
var result = con.addval(2, 3);
/*
con.autoexecute(function(d) { //Wanna do something like this
alert(d);
});
*/
Above things are working as expected, getting result..
Now, Suppose autoexecute(d) method is invoking automatically after a time interval. How can i know if the method is executed ?
So that, I want to create an event(in file2) of autoexecute(d)(in file1).
UPDATE:
I hope this example will help you to understand the issue..
company.js //this is the main file which will be used as a reference in ui.html
function hello(personname) { //this method will invoke automatically after 1 minute..
}
ui.html
<script src="company.js"></script>
<script>
$(document).ready(function() {
function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//
alert("comany.js -> hello function is executed");
}
});
</script>
You can only do this if the functions have the same scope (global scope is the best case scenario). If the autoexecute function has local scope then you cannot to do it.
In essence, override the original function like this...
// keep a reference to the original function
var _autoexecute = autoexecute;
// override the original function with your new one
function autoexecute(d) {
alert("before autoexecute"); // fired before the original autoexecute
_autoexecute(d); // call the original autoexecute function
alert("after autoexecute"); // fired after the original autoexecute
}
Now, whenever autotexecute is called it will call your new function which can handle both before and after events, as well as calling the original function. Just remove the (horrible) alerts and replace with event handlers as required.
To my knowledge, and someone should correct me if I am wrong, there is no way (at least without some library) to detect a function being fired in javascript. Function executions do not fire an event that other functions can 'handle' in that that sense.
In your example you wanted a function to automatically fire after the other function has fired, all you need to do is call the function you want to fire at the end of the one that was "fired" in the first place. Confusing but hope this helps.
function handler(){
alert("main function was fired!");
}
function main(){
//Code of main goes here and then at the end just add:
handler();
}
Now when your "main" has finished its work it will call upon the handler function.
Regardless of where you define the handler function, which can be a different file or same file, so long as it is reachable from within the main's scope, it will be fired at the end of it. It can even be declared after main has been declared, so long as it is declared before main is fired.
I am trying to create a chrome extension. I have the following function in my content script to handle downloads of files:
function handleDownloadFile(urlVal){
console.log("handleDownloadFile called");
}
Then I have the following code to inject a function into the DOM (taken from here: https://stackoverflow.com/a/11811558/3778854):
function injectScript(source) {
var elem = document.createElement("script"); //Create a new script element
elem.type = "text/javascript"; //It's javascript
elem.innerHTML = source; //Assign the source
document.documentElement.appendChild(elem); //Inject it into the DOM
}
injectScript("("+(function(window) {
// functions here
console.log("successfully injected content script"); // works
function foo(url){
$("#downloadPdfButton").click(handleDownloadFile(url));
}
foo("http://url.com/doc.pdf"); // breaks here
}).toString()+")(window)");
upon calling foo("http://url.com/doc.pdf") , it will break saying that handleDownloadFile is undefined. As you can see, I even tried passing window, and then setting window.handleDownloadFile(url) as the click event handler, with no success.
I hope someone can give me some pointers, if this is even possible.
While declaring the handleDownloadFile can you try this -
window.handleDownloadFile = function(urlVal){
console.log("handleDownloadFile called");
}
I'm trying to get better with JavaScript and learn how to utilize my code in functions and keep everything clean. I'm trying to run a function on page-load...
var setColors = function(){
this.init = function(){
$.getJSON('js/colors.json', function(colors) {
$.each(colors, function(i, colors) {
$('<li>', {
text: colors['color'],
'name' : colors['color'],
'data-hex' : colors['hex'],
'data-var' : colors['var']
}).appendTo('#picker');
})
});
}
}
(This is not a color-picker, just a list of colors)
I want setColors() to be executed as soon as the page starts. I read that an anonymous function runs automatically, but this one isn't, I also tried...
$(function(){
setColors();
});
Below the setColors() function and that isn't working ether (The page is just blank). What am I doing wrong and how do I get my function to run on page load? I'm trying to learn so an explanation would be great.
Anonymous functions are not run immediately, you're thinking of Immediately Invoked Function Expressions which happen to often use an anonymous function.
To fix your code:
a) get rid of the this.init function wrapper within the "object" - you're not using it and this.foo only makes sense if you're using new to instantiate an object:
function setColors() {
return $.getJSON(...);
}
Note that returning the $.getJSON() result allows you to register additional deferred object handlers, register error handlers, etc.
b) call the above function in a document.ready handler (which you must do, since the AJAX callback modifies the DOM).
$(setColors);
NB: the latter is a legal way of calling this handler - jQuery will automatically register any function that you pass this way as a document.ready handler. It's similar to writing:
$(function() { setColors() })
but without the extra (useless) function wrapper.
To have that run once the DOM is initialized, you can put it in a ready listener (jQuery):
$(document).on('ready', function() {
setColors();
});
If you want the function to run automatically as soon as it is encountered in the js, after the } that ends the function, add ();
Something like:
function setColors() {
// Code
}();
setColors doesn't return the next function, or call it at the end. YOu could change it to look like:
var setColors = function(){
this.init = function(){
$.getJSON('js/colors.json', function(colors) {
$.each(colors, function(i, colors) {
$('<li>', {
text: colors['color'],
'name' : colors['color'],
'data-hex' : colors['hex'],
'data-var' : colors['var']
}).appendTo('#picker');
})
});
}
init(); // <--- change
}
Which would do the trick for you. You don't even need to "return it" either since the init function itself doesn't return anything, so you could just call it.
I'm developing some library and created this buggy code:
//-------------------
Gmaps = {};
Gmaps.map = new Gmaps4RailsGoogle(); //there exists a default callback function in the created object
function load_map() {
Gmaps.map.callback();
};
window.onload = load_map();
//--------------------
Gmaps.map.callback = function(){ alert('ok'); }
I thought, because the whole page is loaded, that callback would have been changed and alert message displayed.
But it's not the case and I haven't any error message in firebug.
If I then execute Gmaps.map.callback() in console, it works fine.
Is there any reason why the callback isn't overriden?
For context sake, code between --------- is created by the library but developers would be able to override some functions in his html.
You're not executing load_map onload. You're executing it immediately here:
window.onload = load_map();
and storing it's return value inside window.onload, so nothing is happening onload. Just change that line to:
window.onload = load_map;