I have written a small plugin where i have loaded following scripts
wp_enqueue_script('jquery', plugins_url('/js/jquery.min.js', __FILE__),'','1.7',true);
wp_enqueue_script('new-cycle', plugins_url('/js/cycle.js', __FILE__),array( 'jquery' ),'1.0',true);
wp_enqueue_script('new-jcarousellite', plugins_url('/js/jcarousellite.js', __FILE__),array( 'jquery' ),'1.0',true);
wp_enqueue_script('new-fancybox', plugins_url('/js/fancybox.js', __FILE__),array( 'jquery' ),'1.0',true);
and i also have a javascript code to call cycle and fancybox functions ( with parameters/options loaded from options and post_meta tables )
function front_js(){ ?>
<script>
$(document).ready(function(){
$(".video-popup").fancybox();
$(".video_msgs").cycle({speed:'<?php echo get_option("cycle_speed");?>'});
});
</script>
<?php }
this code is added to footer by using add_action('wp_footer', 'front_js');
Now my javascript code is loaded before all the scripts required like
<script>
$(document).ready(function(){
$(".video-popup").fancybox();
$(".video_msgs").cycle();
});
</script>
<script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/twentyfifteen/js/functions.js?ver=20141212'></script>
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/cycle.js?ver=1.0'></script>
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/jcarousellite.js?ver=1.0'></script>
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/fancybox.js?ver=1.0'></script>
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/counter.js?ver=1.0'></script>
and giving error $('...').fancybox()
not a function
I think its because the code is loaded before fancybox.js file where this function is written. I tried to print_scripts functions but its recommended to not to use this and wp_enqueue_script
only works with files not with custom javascript code.
Is there any method to load my custom code after required files loaded or any other way to resolve this type of issue.
It works if I load all the files in header but then it increases page load time that is also not a good approach.
wp_footer
. Shortcut and not recommended method, use the$priority
parameter ofadd_action()
to hook your function later towp_footer