0

In theme development, what is the best way to register and enqueue JavaScript files to avoid problems with plugins?

I want to create a theme which uses scripts like jQuery, Masonry and so on. I downloaded the scripts and added them via the reqister and enqueue function to avoid problems with Wordpress Updates.

function my_scripts() {
  // Register scripts
  wp_register_script( 'my_masonry', get_template_directory_uri() . '/js/masonry.pkgd.min.js', array(), '1.0.0', true ); 
  // Add scripts before closing body tag.
  wp_enqueue_script( 'my_masonry', true );
}

add_action( 'wp_enqueue_scripts', 'my_scripts' );

The other way would be to use the built-in Wordpress scripts to may avoid problems with plug-ins.

function my_scripts() {
  // Add scripts before closing body tag.
  wp_enqueue_script( 'masonry', true );
}

add_action( 'wp_enqueue_scripts', 'my_scripts' );

What is the better approach?

1
  • 1
    Always use core-bundled scripts, rather than custom versions of those scripts. Core, Themes, and Plugins all rely on the assumption that the core-bundled version of a script will be registered and available to be enqueued. Apr 18, 2014 at 12:40

2 Answers 2

2

I would use jquery-masonry included in Wordpress core:

function my_scripts() {
    wp_enqueue_script( 'jquery-masonry', true );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );

If you really need the standalone masonry library, you should use your "first way" but I would not use "my_masonry" as handle for the script, I would use "masonry" if you have not modified the code. Also, use the correct version number of the library (I think your are not really using 1.0.0).

0

function theme_name_scripts() { wp_enqueue_style( 'style- name', get_stylesheet_uri() ); wp_enqueue_script( 'script- name', get_template_directory_uri () . '/js/example.js', array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

add to tour function php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.