javascriptjquerylabjs

Undefined not a function: how to get LABjs to work with jQuery scripts


I'm trying to improve the load time of my web page using LABjs. However I'm getting 'Undefined not a function' in relation to jQuery.cookie('mycookie') which I'm using in my own jQuery script.

I'd be grateful for some advice on how to implement LABjs to deal with this as I don't quite understand the documentation.

Here's the code I have so far:

HTML

I have jQuery and LAB.min.js in the footer of my HTML page

<script type="text/javascript" src="myfolder/jquery1.9.1.js"></script>
<script type="text/javascript" src="myfolder/LAB.min.js"></script>

LAB.min.js file

Here I load my scripts in order. ratings.js depends on jquery-cookie.js, so I've included a wait() first to make sure that jquery-cookie.js is loaded first.

//ALL THE LABjs code is here, but not included on this post!

$LAB.setGlobalDefaults({Debug:true});
.script("myfolder/bootstrap.min.js")
.script("myfolder/jquery-cookie.js") 
.wait() 
.script("myfolder/ratings.js");

ratings.js

ratings.js is a long piece of code contained within the jQuery(document).ready function.

jQuery(document).ready(function() {
 //LOTS OF CODE HERE
    if(jQuery.cookie('mycookie')==null){    
        //LOTS OF CODE HERE
    }   
//LOTS OF CODE HERE
});

I'm getting an error in ratings.js relating to the line of code containing jQuery.cookie('mycookie'). It says "Uncaught type error: undefined is not a function"

From what I understand, jQuery.cookie() isn’t yet defined when I try to pass it to .wait(). What is the best way to get this to work, keeping in mind that I want to keep ratings.js in a separate js file because it contains a lot of code and is one of many similar js files that also throw up the same error when I load them with LABjs.

Many thanks!

Katie


Solution

  • You should be able to remove the link to jQuery in your HTML and just have LABJS to load all of the scripts. This will load jQuery before Bootstrap or your plugin:

    $LAB
      .setGlobalDefaults({Debug:true}) // removed semi-colon
      .script("myfolder/jquery1.9.1.js")
      .wait()
      .script("myfolder/bootstrap.min.js")
      .script("myfolder/jquery-cookie.js") 
      .wait() 
      .script("myfolder/ratings.js");
    

    (Note that you had a semicolon in your code that was likely breaking something too):