How to make JavaScript execute after page load?

前端 未结 24 2349
孤城傲影
孤城傲影 2020-11-21 05:55

I\'m executing an external script, using a

相关标签:
24条回答
  • 2020-11-21 06:02

    These solutions will work:

    <body onload="script();">
    

    or

    document.onload = function ...
    

    or even

    window.onload = function ...
    

    Note that the last option is a better way to go since it is unobstrusive and is considered more standard.

    0 讨论(0)
  • 2020-11-21 06:02

    In simple terms just use "defer" in the script tag.

    .....
    0 讨论(0)
  • 2020-11-21 06:03

    Using the YUI library (I love it):

    YAHOO.util.Event.onDOMReady(function(){
        //your code
    });
    

    Portable and beautiful! However, if you don't use YUI for other stuff (see its doc) I would say that it's not worth to use it.

    N.B. : to use this code you need to import 2 scripts

    <script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js" ></script>
    <script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/event/event-min.js" ></script>
    
    0 讨论(0)
  • 2020-11-21 06:04
    <body onload="myFunction()">
    

    This code works well.

    But window.onload method has various dependencies. So it may not work all the time.

    0 讨论(0)
  • 2020-11-21 06:07

    As Daniel says, you could use document.onload.

    The various javascript frameworks hwoever (jQuery, Mootools, etc.) use a custom event 'domready', which I guess must be more effective. If you're developing with javascript, I'd highly recommend exploiting a framework, they massively increase your productivity.

    0 讨论(0)
  • 2020-11-21 06:08

    I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.

    window.onload = function(){ doSomethingCool(); };
    

    becomes...

    window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };
    
    0 讨论(0)
提交回复
热议问题