Reputation: 377
I would like to know if the following two cases has the exact same effect performance and security wise? Which one is better practice?
Using load event
if (sSessionRole === "admin") {
window.addEventListener("load", function () {
getAjax("api_get_users.php", getUserData);
});
}
function getUserData(ajUserDataFromServer) {
//console.log( "USERS ARE EDITABLE" );
showUsers(ajUserDataFromServer);
}
Using self invoking function
if (sSessionRole === "admin") {
(function () {
getAjax("api_get_users.php", getUserData);
})();
}
function getUserData(ajUserDataFromServer) {
//console.log( "USERS ARE EDITABLE" );
showUsers(ajUserDataFromServer);
}
Upvotes: -2
Views: 805
Reputation: 50807
More than seven years ago, Ben Alman coined the term "immediately invoked functions expression (IIFE, pronounced iffy)" to describe what you're calling a "self-invoking function". That term is the one which seems to have caught on.
No. The first one sets the activity to take place on the load event of the window. The second one runs it immediately. Presumably your AJAX call is asynchronous, so the change to the DOM will still not happen for some short time, but there is a difference here. If the value returned by this AJAX call varies over time, you could get different results in your showUsers
call.
As a comment pointed out, the IIFE here is entirely unnecessary. It does nothing but add a superfluous function into the mix.
Given that you have different behaviors, questions of performance should be considered moot, except in that they could have different perceived times to load because of your different start time for this process. That you would need to test for yourself.
I see no difference likely in security issues.
Upvotes: 0