Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

javascript - How to enqueue glider.js?

I've built a static site in html, css and js that I've converted into a wordpress theme. I've used glider.js for an image slider. The slider works perfect locally as a static html/css/js site.

Converting the site to a wordpress template, I have two js files and have enqueued both my app.js file and glider.min.js in my functions.php file.

// Add javascript start
function load_js() {
    wp_register_script('javascript', get_template_directory_uri() . '/app.js', array(), false, true);
    wp_enqueue_script('javascript');
}

add_action('wp_enqueue_scripts', 'load_js');

//glide js

function load_glide() {
    wp_register_script('load_glide', get_template_directory_uri() . '/glide.min.js', array(), false, true);
    wp_enqueue_script('load_glide');
}

add_action('wp_enqueue_scripts', 'load_glide');

// Add javascript end

When I view the wordpress site live glider.js doesn't work. I get the console error "Uncaught ReferenceError: Glide is not defined". The js file glider.min.js is in the right place when I check the sourcecode for the page in dev tools. Why am I getting "Glide is not defined" when glider.min.js has been enqueued? the "Glide" object is in app.js but needs glide.min.js.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem here is WordPress related and how it handles loading scripts.

Your app.js file depends on glide.min.js, so you have to explicitly tell that when registering scripts into the WordPress with wp_register_script function. It accepts an array of dependent scripts ids as a third parameter.

// Add javascript start
function load_js() {
    wp_register_script('javascript', get_template_directory_uri() . '/app.js', array('load_glide'), false, true);
    wp_enqueue_script('javascript');
}

add_action('wp_enqueue_scripts', 'load_js');

//glide js

function load_glide() {
    wp_register_script('load_glide', get_template_directory_uri() . '/glide.min.js', array(), false, true);
    wp_enqueue_script('load_glide');
}

add_action('wp_enqueue_scripts', 'load_glide');

// Add javascript end

Note that I added the load_glide id when registering app.js file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...