Wordpress插件根据需要加载js和css

Wordpress plugin load js and css on demand

本文关键字:加载 js css 插件 Wordpress      更新时间:2023-09-26

我用shortcode创建了插件。只有当我使用插件(我帖子中的短代码)时,我才想加载插件的js和css。我发现了一些例子,我创造了这样的东西。这是正确的方式吗?一切正常,但我在页面源代码中看不到这些脚本(我检查了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_enque_style()和wp_engue_script()在这个地方不起作用,您应该在另一个函数中使用它们,例如,用于wp_enque脚本钩子的my_scripts_method()。

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