首页 > 解决方案 > Why is my page content loading before my header script

问题描述

assets/javascript/hdr.js:

jQuery(function($) {
     console.log("testtt");
     function returnT() {
          return true;
     }
});

functions.php:

function hdr_scr() {
    wp_enqueue_script( 'h_scr', get_stylesheet_directory_uri() . 'assets/javascript/hdr.js', array(), false, false );
}

add_action( 'wp_enqueue_scripts', 'hdr_scr' );

https://mypage.com/my-pos (TwentyTwenty Child: pos Template (my-pos.php)):

    ...
    <!-- toward bottom of template -->
    <script>
        debugger;
        var t = returnT();
    </script>
    </div> <!-- end container...... -->

</main><!-- #main -->

The above scripts/page are as it is setup in my site. The issue I am coming across is, var t = returnT(); is called even before the console.log("testtt"); in my hdr.js file. That is causing an error.

Based on my setup, the page should have hdr.js content ready, for the page to invoke but for some reason it's not happening.

How can I resolve it?

标签: javascriptwordpressdeferred

解决方案


The thing is that your code waits for DOM to be loaded, and then executes, because:

  • $(document).ready(function() { ... }) is the most used form for executing code when the DOM is ready
  • $(function() { ... }) is equivalent to the previous (it's a shorthand)
  • jQuery(function($) { ... }) it's a "safe" version of the same thing ($ is available inside the function, no matter what it was set before)

So, your code executes

var t = returnT();

before

jQuery(function($) {
  console.log("testtt");
  function returnT() {
    return true;
  }
});

so the returnT() function does not exist at the time you call it.

Either move the returnT() so it doesn't "wait" for DOM to be ready, or set the function call to wait for DOM ready too.


推荐阅读