javascript - 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?
解决方案
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.
推荐阅读
- c# - bot framework v3中的自适应卡片可以包含动态下拉菜单吗
- c# - 在 C# 中使用泛型掌握数据缓存
- typescript - 打字稿泛型+条件类型不可分配给类型错误
- php - 我的数据库在 phpMyAdmin 上不可见,但在 mysql 的数据文件夹中可用
- ios - 在swift中,如何在顶部保留一个UIViewController().view?like UIAlertController
- amazon-web-services - 无法删除 AWS Elastic Beanstalk 应用程序
- sql - 如何使用纯 SQL 获取增量记录?
- c++ - 模板参数推导算法(作为字符串)?
- c# - 为什么我提供数据时数据库会添加空值?
- php - 如何将方法调用转发到 Laravel 中的另一个对象?