where to put code for after dom is ready

Discussion in 'HTML & Website Design' started by jazzzyman, Aug 27, 2013.

  1. #1
    im trying to run addthis after the dom is ready: http://support.addthis.com/customer/portal/articles/381221-optimizing-addthis-performance#.UhyJfX9yUsc

    where do i put the code that is initialized after the dom is ready?
     
    jazzzyman, Aug 27, 2013 IP
  2. ekim941

    ekim941 Member

    Messages:
    74
    Likes Received:
    7
    Best Answers:
    7
    Trophy Points:
    33
    #2
    Before the closing body tag, after all of your other script tags
    <!--If you are using jQuery-->
    <script type="text/javascript">
    $(document).ready(function(){
    initAddThis();
    });
    </script>
    
    <!--If you are just using javascript without jQuery this MIGHT work-->
    <script type="text/javascript">
    window.onload=function(){
    initAddThis();
    }
    HTML:
    This isn't tested but it should get you started.
     
    ekim941, Aug 27, 2013 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    Sneaky trick, 99.99999999999% of the DOM is built and available to scripts right before </body> in the markup. You can load/activate the script there and it will typically apply itself before CSS is applied to the DOM... without wasting time dicking around with onload.

    <body>
    <div id="test">Simple test</div>
    <script type="text/javascript">alert(document.getElementById('test').innerHTML);</script>
    </body>
    Code (markup):
    If the DOM wasn't available/built yet, the above would throw an error.

    In most browsers it's also faster to include in BODY instead of HEAD, since things in HEAD are loaded in order AFTER body in the order listed... It's also handy to know since onload doesn't fire until after CSS and images are loaded, while code in <body> is run during DOM construction (which pretty much means after DOM construction if right before </body>) letting you apply classes or changes to the DOM before CSS is loaded or applied!
     
    deathshadow, Aug 28, 2013 IP