I have a custom jquery-based slider on homepage of a WordPress site. I'm loading jQuery (jquery.js) and the slider js (jquery.advanced-slider.js) using below code in my functions.php file of my theme.
function my_load_scripts() {
if (!is_admin()) {
wp_enqueue_script("jquery");
if (is_home()) {
wp_enqueue_script('theme-advanced-slider', get_template_directory_uri().'/js/jquery.advanced-slider.js', array('jquery'));
wp_enqueue_script('theme-innerfade', get_template_directory_uri().'/js/innerfade.js', array('jquery'));
}
}
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
Now I put the below code in my header.php file BEFORE wp_head();
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function () {
//Slider init JS
$j(".advanced-slider").advancedSlider({
width: 614,
height: 297,
delay: 1000,
pauseRollOver: true
});
});
</script>
It's obvious here that my jquery.js and jquery.advanced-slider.js load after the JavaScript code above and thus my slider doesn't work. If I put it after wp_head() call in <head> the slider works.
But if I put it after wp_head() wouldn't that be a hack? I want my code to be clean. As twentyeleven theme clearly says
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
I'm very confused here. I might be missing something very simple clue here. But help me out guys. What would be the best way to put the JavaScript before wp_head() and yet have it load after jquery.js and slider.js have loaded?
Add your script block to the bottom of the HTML page, just before the </body>.
Your slider init JS code won't get executed until the full DOM has been parsed in the browser anyway so there is no disadvantage to this.
In fact web performance experts like Steve Souders suggest that script blocks should be added at the end of your HTML page as script blocks block rendering and the page appears to load faster this way.
As per wordpress function reference:
The safe and recommended method of adding JavaScript to a WordPress generated page is by using wp_enqueue_script(). This function includes the script if it hasn't already been included, and safely handles dependencies.
If you want to keep your "code clean" you might rethink how your js is organised.
My approach with wordpress is to (usually) keep a scripts.js for all initialisation and small scripts and separate file(s) for plugins. But everything depends how big and how many files you have - you want to avoid too many http requests and files that are hard to manage.
As well, wp_enqueue_script lets you place the scripts in the footer.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
Wait for loading jQuery with window.onload function, once jQuery file and other js / content loaded then window.onload function will be fire.
<script type="text/javascript">
window.onload = function(){
var $j = jQuery.noConflict();
$j(".advanced-slider").advancedSlider({
width:614,
height:297,
delay:1000,
pauseRollOver:true
});
}
</script>
The code that you are adding to the bottom of the page should be externalized to it's own file and added with the wp_enqueue_script(); function like shown below.
Note the use of the 'true' directive at the end of each call to wp_enqueue_script. That tells WordPress that you want them included at the wp_footer(); hook (instead of the wp_head(); hook) which should appear directly before the closing </body> tag - as per the performance best practices that others have mentioned.
function my_load_scripts() {
if (is_home()) {
wp_enqueue_script('theme-advanced-slider', get_template_directory_uri().'/js/jquery.advanced-slider.js', array('jquery'), true);
wp_enqueue_script('theme-innerfade', get_template_directory_uri().'/js/innerfade.js', array('jquery'), true);
wp_enqueue_script('your-custom-script', get_template_directory_uri().'/js/yourcustomscript.js', array('jquery'), true);
}
}
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
I've removed the jQuery enqueue line you had included because you shouldn't need to register the jQuery script as it's already registered by the WP core and since you have defined it as one of the dependencies it will be included for you.
Since you have wrapped it all in an is_home() conditional statement the all 3 of these files - plus jQuery - will be included in just the homepage.
An easier - but maybe not so nice - hack is to simply add a 1-millisecond timeout
setTimeout(function () {
jQuery('#text-6').insertBefore('#header');
}, 1);
get_template_directory_uri() does give you the theme directory, but this is not what you want if you are using a Child Theme.
get_stylesheet_directory_uri() will give your the directory of your "current theme", so in either case, it is safest to use.
Related
I have a widget with some custom js:
class ImagePreviewWidget(ClearableFileInput):
...
class Media:
css = {
'all': ('css/image-preview-widget.css',)
}
js = ('js/image-preview-widget.js', )
The custom js uses jQuery, which is loaded independently, so I need to wrap my module initialization in:
window.onload = function() {
cusomJsStart();
};
Which is not very clean (one problem is that I am maybe interfering with other window.onload calls). Is there a better way to load the widget javascript?
EDIT
Just to make it clear: the whole point of this question is that jQuery is not yet loaded when the script runs, and that the script loading order is outside my control.
Instead of setting window.onload you should use addEventListener:
window.addEventListener("load", customJsStart);
(If you need to support IE<9 then some fallback code is required - see the MDN link above).
Even nicer would be if you could tell Django to add a defer attribute to the scripts you pass in the Media class, but it doesn't support that yet.
There is nothing better than pure Javascript ! Alternatively you can use JQuery like this :
$(function(){
cusomJsStart();
});
But with this method your page will be heavier because of JQuery source file loading.
Or you can put your cusomJsStart() at the end of your HTML file, but it's not clean at all !
You did the right choice.
I want to use a read-more jQuery script on my wordpress website. The script I want to use can be found on https://github.com/jedfoster/Readmore.js. I've used several stackExchange topics and the following tutorial http://www.ericmmartin.com/5-tips-for-using-jquery-with-wordpress/. But I still don't have it working. What have I done?
Created a folder in the theme directory called "custom_js". In this folder I copied the script called "readmore.js".
Added the following piece of code on the top of the functions.php file located in the theme directory:
//this goes in functions.php near the top
function my_scripts_method() {
// register your script location, dependencies and version
wp_register_script('custom_script',
get_template_directory_uri() . '/custom_js/read_more.js',
array('jquery'),
'1.0' );
// enqueue the script
wp_enqueue_script('custom_script');
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
The code in the readmore.js file is surrounded by this code:
;(function($) {
})(jQuery);
Did I implement the script the right way? If no, then what did I do wrong? And if I did implement the script the right way, how do I call the script so there will be a read-more button on my wordpresspage?
Everything looks fine apart from how you wrap the readmore.js code. You need to wrap it like this:
jQuery(function ($) {
/* You can safely use $ in this code block to reference jQuery */
// readmorejs contents here.
});
as opposed to
;(function($) {
})(jQuery);
As I can see from the plugin source it applies to article tag, so make sure your posts are wrapped in that tag.
Or you can change it from $('article').readmore(); to $('whatever article wrapper').readmore();, for example $('div.post').readmore();.
Also make sure that script is loaded and loaded after jQuery.
I bought a theme where pages were all HTML with JS scripts loaded at the bottom. I modified the theme and now have PHP files with the following (quite standard, with php includes to load the required content) :
index.php
header.php
menu.php
footer.php
content1.php
content2.php
content3.php
...
All the scripts are still loaded at the end, in footer.php.
My problem lies in the fact that in each content pages I need specific scripts, for exemple content1.php needs script1.js, content2.php needs script2.js...
Here is where I have trouble understanding the proper way of doing it :
I could load all scripts (script1.js, script2,js and script3.js) in the footer therefore whichever content is loaded, the required script will be loaded anyway. But I end up loading scripts that are not being used.
For example, I have a script that generates and displays a table from a json array (which is generated using php and a mysql query). This table is only displayed in content1.php.
I don't want to load this script in the footer as it will then be executed each time a page is displayed even if we don't need it. And I can't include it in content1.php as it requires other scripts (jQuery) which is loaded in the footer, ie. after the php include itself.
Does that make sense ?
Use PHP conditionals (either an if/else or switch, which might be better) to check the URL value and load the appropriate scripts for the page in header.php. Very rough example below.
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'content1') !== FALSE) {
echo '<script src="script1.js"></script>';
}
elseif (strpos($url,'content2') !== FALSE) {
echo '<script src="script2.js"></script>';
}
Why not load the ones you need more often in the header file i.e. jquery and call the optional files at the bottom of the page where they needed, there by removing all calls from the footer
You may be better off combining the files and including the new file in the footer. One file would result in fewer requests, but keep an eye on the file size.
Done a small thing few years ago as follows:
<?php
if(getPageJsname()!='') {
?>
<script type="text/javascript" src="jquery-code-<?php echo getPageJsname(); ?>.js"></script>
<?php
}
?>
function getPageJsname() {
return $scriptname = trim($_SERVER['SCRIPT_NAME'], "/");
}
After this you can rename all the javascript files as follows:
for page content1.php js name will be jquery-code-content1.js
and vice-versa
See if this help with something
Take this out of the footer:
<script></script>
</body>
</html>
And put it in each page accordingly.
in content1.php create a var
$script='script1.js';
the same in content2.php
$script='script2.js';
and content3.php
$script='script3.js';
finally in footer.php
echo '<script src="'.$script.'"></script>';
Well, easiest and obvious solution would be to load jQuery before content blocks start. While it is recommended and good to include scripts at the bottom, it's not that of a cornerstone. It is also recommended to combine and compress your JS, so you can generate one compressed JS for all your pages.
But you can also try to load scripts via AJAX after document is rendered. There is http://api.jquery.com/jQuery.getScript/
And you know what content is loaded by that point.
$(document).ready(function() {
if ($("#content1").length > 0) { ... }
});
You can also try to wrap your code in function to postpone it's execution untill jQuery is also loaded.
I am not sure if I am utilizing head.js correctly. In the header of my html document I call the head.js file via:
<script src="/scripts/head.min.js" type="text/javascript"></script>
Then right before the closing < / body > tag in the html page, I call the following file:
<script src="/scripts/load.js" type="text/javascript"></script>
In the load.js file I have the following code:
head.js(
{livechat: "/scripts/livechat.js"},
{jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"},
{jquerytools: "http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"},
{slider: "/scripts/jquery.nivo.slider.pack.js"},
{prettyphoto: "/scripts/jquery.prettyPhoto.js"},
{sliderfunctions: "/scripts/slidercode.js"},
{functions: "/scripts/functions.js"}
);
Does the above code cause the javascript files to execute in the same exact order they are listed or do they sometimes execute out of order?
I ask because the slider initially only functioned if I utilized the following code within load.js:
head.ready("slider", function() {
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
I was able to get around this by moving the above code to an external file called slidercode.js which contained the following code:
$(window).load(function() {
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
But I am not sure if I am going about this the correct and most efficient way as this is my first time using head.js. Basically from the javascript files in loader.js I need to make sure:
jquery loads first.
Once jquery has fully loaded then jquerytools loads
After jquery is fully loaded, it should load slider first and then prettyphoto.
Then sliderfunctions should load as it is dependent on slider,
Lastly, functions should load as it is dependent on jquery and jquerytools.
You should call the scripts like this: (remove the http as well, it's not needed. Also Jquery always loads first of any scripts. in this case headJS has priority then jquery then all your scripts)
<script src="/scripts/head.min.js" type="text/javascript"></script>
// this loads asyncrounously & in parallel
head.load("//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js", "//cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js", "/scripts/jquery.nivo.slider.pack.js", "/scripts/jquery.prettyPhoto.js", "/scripts/slidercode.js", "/scripts/functions.js");
Then right before the closing < / body > tag in the html page, I call the following file:
<script>
head.ready(function () {
// some callback stuff
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
<script>
Does the above code cause the javascript files to execute in the same
exact order they are listed or do they sometimes execute out of order?
Yea, they load asyn, but execute in order.
I think head.ready("slider", function() {} );should also work even if you place it outside of load.js. Try adding it after load.js script block.
I have been trying to get malihu's Simple jQuery fullscreen image gallery ( http://manos.malihu.gr/simple-jquery-fullscreen-image-gallery ) to work with my Wordpress theme, but for some reason I'm having trouble getting the script to run. I'm calling both the CSS and javascript normally as with other plugins in the functions.php file, but the javascript doesn't seem to be taking effect to make the gallery. I currently have the following code to call the CSS in the header and the javascript in the footer. Am I missing something?
function malihu_gallery() {
if (!is_admin()) {
// Enqueue Malihu Gallery JavaScript
wp_register_script('malihu-jquery-image-gallery', get_template_directory_uri(). '/js/malihu-jquery-image-gallery.js', array('jquery'), 1.0, true );
wp_enqueue_script('malihu-jquery-image-gallery');
// Enqueue Malihu Gallery Stylesheet
wp_register_style( 'malihu-style', get_template_directory_uri() . '/CSS/malihu_gallery.css', 'all' );
wp_enqueue_style('malihu-style' );
}
}
}
add_action('init', 'malihu_gallery');
I'm thinking that I may need to ready the script with something similar to the following, but not sure if I'm on the right track.
function gallery_settings () { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#container').malihu_gallery();
});
</script><?php
Any help greatly appreciated!
Thanks
If you want any event to work in jQuery you will want it inside document ready. This will load it after the DOM is loaded and before the page content is loaded.
$(document).ready(function() {
// your stuff inside of here
});
Not sure based on what you have shown above but try some basic debugging, see if you can call functions when you paste your code into the console. Or if you want to create a fiddle I will take a look.