简体   繁体   English

WordPress插件按需加载js和css

[英]Wordpress plugin load js and css on demand

I created plugin with shortcode. 我用简码创建了插件。 I want to load js and css of my plugin only if i use the plugin(the shortcode in my post). 我只想在使用插件(我帖子中的短代码)的情况下加载插件的js和css。 I found few examples and i created something like this. 我发现了几个例子,并创建了类似的东西。 Is it correct way? 这是正确的方法吗? Everything works but i can't see these scripts in page source (i checked Firefox and chrome) 一切正常,但我在页面源代码中看不到这些脚本(我检查了Firefox和chrome)

   public function __construct(){       
        add_shortcode( $this->tag, array($this, 'run_yoolek' ) );
        add_action( 'wp_enqueue_scripts',  array( $this, 'register_my_script' ) );  
    }

    public function run_yoolek(){

        wp_enqueue_style('yoolek-googlemap-simple-css');
        wp_enqueue_script('google-maps');
        wp_enqueue_script( 'yoolek-googlemap-simple-js' );

        ob_start();
        ...
        return ob_get_clean();
    } 

    public function register_my_script() {
        wp_register_style( 'yoolek-googlemap-simple-css',plugins_url( '/style.css' , __FILE__ ) );
        wp_register_script( 'google-maps', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAM10sMY' );
        wp_register_script( 'yoolek-googlemap-simple-js', plugins_url( '/script.js' , __FILE__ ) );

    }   

wp_enqueue_style()和wp_enqueue_script()在该位置不起作用,您应该在另一个函数中使用它们,例如,my_scripts_method()用于wp_enqueue_scripts挂钩。

  add_action( 'wp_enqueue_scripts', array($this, 'my_scripts_method') );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM