Javascript Run Function After Page Load

北城以北 提交于 2019-11-29 08:49:47
hallvors

This code has several issues:

if (addEventListener in document) { // use W3C standard method
    document.addEventListener('load', meerfirst(), false);
} else { // fall back to traditional method
    document.onload = meerfirst();
}
  1. You need to put quotes around addEventListener in the if statement. You're looking for a property name in document, so the name needs to be a string: if( 'addEventListener' in document )

  2. You want to refer to the function by name in the addEventListener statement, not call it immediately. You should remove the parentheses - use just meerfirst instead of meerfirst().

  3. Assigning to document.onload has no effect. See my answer to window.onload vs document.onload and use window.onload instead.

  4. After changing the assignment to window.onload you also need to remove the parentheses. Again, you're just referring to the function by name and don't want it to actually be called at this point.

  5. Finally, I recommend listening for DOMContentLoaded rather than load - unless you are going to run some code that needs to wait until all images are loaded.

Pass the function itself as the callback

addEventListener('load', meerfirst, false);
                  // no parens! ^^

by putting the parentheses you instead call the function immediately (before things load) and pass its (useless, non-function) return value to addEventListener.


BTW, since you already know what browser you will use the code on, why are you doing that feature testing in the start?

Try:

window.onload = function() 
{

meerfirst();

};

Your answer is nested nicely within O'Reilly's "Javascript: the Definitive Guide"

// Register the function f to run when the document finishes loading.
// If the document has already loaded, run it asynchronously ASAP.
function onLoad(f) {
    if (onLoad.loaded) // If document is already loaded
        window.setTimeout(f, 0); // Queue f to be run as soon as possible
    else if (window.addEventListener) // Standard event registration method
        window.addEventListener("load", f, false);
    else if (window.attachEvent) // IE8 and earlier use this instead
        window.attachEvent("onload", f);
}
// Start by setting a flag that indicates that the document is not loaded yet.
onLoad.loaded = false;
// And register a function to set the flag when the document does load.
onLoad(function() { onLoad.loaded = true; });

This will not only run when the browser finishes loading but it will also handle cross-browser discrepancies. Enjoy :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!