You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在functions.php中Enqueue JavaScript时内外文件加载顺序异常致代码失效求助

Fixing Script Loading Order in WordPress Functions.php

The core issue here is that your internal JavaScript file isn’t marked as dependent on jQuery—so WordPress doesn’t know to load jQuery first. Let’s adjust your code to enforce the correct loading order using WordPress’s built-in dependency system.

Corrected Code Example

function _tandt_scripts() {
    $my_js_ver = date("ymd-Gis");
    
    // Replace default jQuery with CDN version
    wp_deregister_script('jquery');
    wp_register_script(
        'jquery',
        'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js',
        array(), // jQuery has no dependencies here
        '2.1.3',
        true // Load in footer for better performance
    );
    
    // Enqueue your internal script with jQuery as a dependency
    wp_enqueue_script(
        'custom-internal-script', // Unique handle for your local script
        get_template_directory_uri() . '/path/to/your/internal-script.js', // Update this path to match your file
        array('jquery'), // Critical: tells WordPress to load jQuery BEFORE this script
        $my_js_ver,
        true // Load in footer to avoid render-blocking issues
    );
}
add_action('wp_enqueue_scripts', '_tandt_scripts');

Key Fixes Explained

  • Dependency Declaration: Adding array('jquery') to your internal script’s enqueue call is the magic here. WordPress will automatically prioritize loading jQuery first because it recognizes your local script depends on it.
  • Footer Loading: The true parameter ensures scripts load at the end of the page, which not only improves performance but also reduces chances of DOM-related errors (since the page will be fully loaded before scripts run).
  • Automatic jQuery Enqueue: You don’t even need to explicitly call wp_enqueue_script('jquery')—WordPress will load it automatically when it processes your dependent internal script.

Quick Checks

  • Verify the path to your internal script: Use get_template_directory_uri() for parent themes or get_stylesheet_directory_uri() for child themes to ensure the file path is correct.
  • If you add other external scripts later that rely on jQuery, repeat the dependency pattern by adding array('jquery') to their enqueue calls.

内容的提问来源于stack exchange,提问作者J Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:45:22