1

I'm building a CMS with PHP/MySQL, and so far using jQuery to add sorting and filtering to table columns. Usually, it works great, but occasionally the sorting and filtering elements won't load - this only happens if I manually refresh the page (never if I access it through a link), and only sometimes. There are times when I can refresh several times before it happens, where other times it can happen several times in a row.

When the issue occurs, Firebug's Console tells me one or both of the following:

ReferenceError: jQuery is not defined

ReferenceError: $ is not defined
$(document).ready(function(){

(and sometimes: TypeError: $(".tablesorter").tablesorter is not a function)

When everything loads fine, the Console is blank.

My header file, which loads on all pages of the CMS, starts with:

<?php ob_start(); ?>
<!DOCTYPE html>
<html>
<head>
    <meta name="robots" content="noindex">
    <title><?=$pg_title." - ".$site_name;?> | Lucid <?=$ver_num;?></title>
    <link href="/favicon.gif" rel="icon" />
    <link rel="stylesheet" href="css/styles.php" type="text/css" />
    <script src="js/jquery-1.8.3.min.js" async></script>
    <script src="plugins/jquery-tablesorter/js/jquery.tablesorter.min.js" async></script>
    <script src="plugins/jquery-tablesorter/js/jquery.metadata.js" async></script>
    <script src="plugins/jquery-tablesorter/addons/pager/jquery.tablesorter.pager.min.js" async></script>
    <script src="js/picnet.table.filter.min.js" async></script>
</head>

Then in the footer file, I call various functions:

 <script async>
    $(document).ready(function(){
        function validateNumber(event) {
            var key = window.event ? event.keyCode : event.which;

            if (event.keyCode == 8 || event.keyCode == 46
             || event.keyCode == 37 || event.keyCode == 39) {
                return true;
            }
            else if ( key < 48 || key > 57 ) {
                return false;
            }
            else return true;
        };
        $('[class=sort-order]').keypress(validateNumber);
        $(".tablesorter").tablesorter({ 
            textExtraction: 'complex'
        }); 
        var options = {
            filterDelay: 100,
            clearFiltersControls: [$('.filter-clear')]
        };
        $('.tablesorter').tableFilter(options);
        $('input:not(.filter)').live("change", function () {
            window.onbeforeunload = function () { return "Your changes have not been saved, if you leave the page you'll lose them" };
        });
    });
</script>
</body>
</html>
<?php 
ob_flush();
?>

I'm aware that this is a fairly common problem, but I feel I've tried all the solutions (including those listed here: JQuery - $ is not defined)

I've tried using setTimeout to delay the loading of all scripts other than jQuery for up to one second - doesn't help.

I've tried checking whether jQuery is defined with if(jQuery) - it always is.

Firebug's Net tab shows me that the jQuery file has the status 304 Not Modified, regardless of whether the issue has occurred.

As far as I can tell all my spelling and syntax is fine, which it should be given that it does work most of the time.

I've tried loading jQuery from an external website instead of locally - no difference.

I should point out that I'm using XAMPP to develop the CMS locally, rather than a remote server, so I thought it might be something amiss with my apache config. I then uploaded everything to a remote server and found the problem was worse, which suggests it's something to do with the speed of loading the page, maybe the async? But I don't know what else I can do to make sure jQuery loads before loading any scripts...

Community
  • 1
  • 1
don_karnia
  • 15
  • 1
  • 3

1 Answers1

5

The async attribute on script elements means that the parsing of the HTML may continue before the script is downloaded and evaluated. Which means that subsequent script elements cannot rely on previous ones having been evaluated — which means that the jQuery plug-ins you're loading after jQuery fail, because jQuery isn't loaded yet.

Specifically:

<script src="js/jquery-1.8.3.min.js" async></script>

tells the browser you want that script, but not to hold things up waiting for it. Then:

<script src="plugins/jquery-tablesorter/js/jquery.tablesorter.min.js" async></script>

says the same thing. This sets up a race condition, there is no longer any order to those two script elements, and so sometimes the second one gets evaluated first. Since the second one requires jQuery, that fails.

To fix it, you need to remove the async attribute. If your goal is for the page to render more quickly, without waiting for scripts, move all of your scripts to the end of the body (e.g., just before </body>). But note that that can mean a brief moment when the user tries to interact with the page before event handlers are hooked up and such.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Brilliant, thank you, such a simple fix. I'll admit I was just blindly following Firebug's Page Speed tool when it suggested using async... – don_karnia Dec 01 '12 at 12:36