dpziir0079
dpziir0079
2016-08-23 09:59

Wordpress - wp_enqueue_script / wp_enqueue_style不起作用

I have coded myself a little WP-Plugin, where I do

wp_enqueue_script('jquery');        
wp_enqueue_script('myapp1', $pluginpath . 'build/js/app.min.js', array('jquery')); 
wp_enqueue_style("myapp2", $pluginpath . 'build/css/style.css');

while testing on my localhost, everythink worked fine, so I uploaded everything to my server and there, my plugin works, too, but the app.min.js and the style.css is not included(?)

what could be the cause for this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douchuopiao9002 douchuopiao9002 5年前

    Files that are referenced with wp_enqueue_script()/wp_enqueue_style() are used in the wp_head() function.

    By the time your shortcode is evaluated this part is already finished, so your files will never be referenced.

    You have to add your style using the wp_enqueue_scripts action:

    function my_scripts() {
        wp_enqueue_style("myapp2", $pluginpath . 'build/css/style.css');
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts' );
    

    There is no way around that, because the style belongs in the head.

    For your JS though, you can use another parameter to load it in the footer:

    wp_enqueue_script('myapp1', $pluginpath . 'build/js/app.min.js', array('jquery'), "1.0", true); 
    

    You can add this in your shortcode so at least the JS will only be loaded when it is needed.

    (The version number can be anything you want, it is useful to increment it when you release new version of your JS file, so browsers don't use old versions from cache.)

    点赞 评论 复制链接分享
  • dreamfly0514 dreamfly0514 5年前

    Well first thing that comes to my mind is that the $pluginpath variable is set incorrectly. Check the browser console if the files gets enqueued at all and if they do they should produce 404 errors. If the error is produced then you can see the file path and check if it is correct (which should not be if it seems that files are missing).

    Also, you don't have to enqueue jQuery because WordPress core does that.

    点赞 评论 复制链接分享