Script to run at completion of Page Loading

On the home page I a have 2 lines of code I would like to run in JavaScript.

Where should I put these two lines of code.

Read More

Does WP have a specific way to do this. Or should I just pick the last .js file that loads and add it there?

Related posts

Leave a Reply

2 comments

  1. Depends on what the javascript is. What is it? Add the js code to your question.

    If it’s an externally loaded script that does nothing more than track page loads – like google analytics or other stat counter code – there’s no reason to use wp_enqueue_script. Sometimes you can simply add it to footer.php or header.php

    If you need the js to run specifically when the page is finished loading, then you need to wrap it in a jQuery function called .ready()

    jQuery(document).ready(function($) {
      // Code using $ as usual goes here.
    });
    

    See http://api.jquery.com/ready/

    And if the code is jQuery, you may need to wrap it in a noConflict wrapper to prevent conflicts with other js.

    <script type="text/javascript">
      $.noConflict();
      jQuery(document).ready(function($) {
        // Code that uses jQuery's $ can follow here.
      });
      // Code that uses other library's $ can follow here.
    </script>