Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script doesn't work unless executed in footer

This is a weird situation. Despite making sure that all of its dependencies are loaded before it (in my case it's only jQuery library), my script doesn't work when loaded in the head section (i.e. <head>), but does its job when loaded in the footer (somewhere above </body> tag).

Since that's not clear enough, let me give a live example. This is the web page. Now, view the source of the page, and in there, this is the code I am talking about.

<script type='text/javascript'>
/* <![CDATA[ */
var yjlSettings = {"gifUrl":"http:\/\/whatthenerd.com\/wp-content\/themes\/reddlec\/images\/ajax-loader.gif","autoGrow":"enable"};
/* ]]> */
</script>
<script type='text/javascript' src='http://whatthenerd.com/wp-content/themes/reddlec/js/no-reload-comments.js?ver=3.3.2'></script>

What it's supposed to do is allow users to post comments without reloading the page. (Please feel free to test comment on the page :) ) -- but it's doesn't. Why?

PS: Like I said earlier, everything works when the aforementioned scripts are loaded just before the </body> tag. I don't really see what could be causing the conflict.

like image 409
its_me Avatar asked Dec 08 '25 13:12

its_me


1 Answers

Your script goes immediately out to find elements in the DOM:

var $commentlist = jQuery('.commentlist');
var $respond = jQuery('#respond');

Two examples found within the script. These items don't exist at the time the header is being loaded, but they do exist by the time the end of your body is reached. If you want to load this from your header, you need to wrap this in a document ready block:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

This makes it safe to load at the top of your page by delaying the execution of your code until the document has fully loaded, and the DOM is constructed.

More about ready online at: http://api.jquery.com/ready/

like image 96
Sampson Avatar answered Dec 10 '25 03:12

Sampson