Loading jQuery & javascript in footer
-
Hi, I would like to load the bundled jQuery and my other javascript files in the footer. I put the following code in my functions.php and it loaded the javascript files in the footer via the wp_footer() hook. Is this the right way? Will it cause conflicts with plugins?
function load_javascript_files () { wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/js/bootstrap.min.js' ); } add_action( 'wp_footer', 'load_javascript_files' );
-
You actually want to use
wp_enqueue_scriptsinstead.You can do it with just a few changes:
function load_js_files(){ wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/js/bootstrap.min.js', array( 'jquery' ), null, true ); } add_action( 'wp_enqueue_scripts', 'load_js_files' );That way WordPress can handle any dependencies that are required by your files. ( Which is what the
array( 'jquery' )part does. 😉 And it will also load the files in sequence.Thanks, I just tried your method and it loads bootstrap.min.js in the footer all well and good, but not jquery. It still loads jquery in the head. I think the reason for that is because jQuery is pre-registered by WP core files without the parameter to load in the footer.
I’m trying to get them both to load in the footer, with jquery first (required when using bootstrap.min.js). So far, my code has been the only method i’ve found to load them both in the footer in the correct sequence.
You could try:
function load(){ wp_enqueue_script( 'jquery', '', '', '', true ); wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/js/bootstrap.min.js', array( 'jquery' ), null, true ); }As you said it may cause some issues with plugins. That’s one way I can think of but I haven’t tried it yet. 🙂
The topic ‘Loading jQuery & javascript in footer’ is closed to new replies.