1

I am trying to load a script with a function like:

$.getScript('/js/mymy.js').done(function(){ 
    if(readCookie('my_cookie', 'yes')){
        /* do sth here */
    }
});

or

$.getScript('/js/mymy.js',function(){   
    if(readCookie('my_cookie', 'yes')){
        /* do sth here */
    }
});

where "readCookie" is defined in mymy.js but i get an error "readCookie" is not defined...

Here 1 & 2 is where i have got help how to do, but it does not work... Any Ideas?

i do use jQuery 1.8.0

mymy.js does contain a function:

jQuery(document).ready(function() {
  function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  /** There is sth much more here **/
  ...
  /** There is sth much more here **/
});
5
  • 1
    can you post the contents of mymy.js? Commented Mar 12, 2015 at 16:18
  • added definition of readCookie Commented Mar 12, 2015 at 16:23
  • 1
    thanks, and that function is not within another function right? Commented Mar 12, 2015 at 16:24
  • It is standonly function in jQuery(document).ready(function() { }}; Commented Mar 12, 2015 at 16:30
  • 2
    that's your problem, it's within that document ready function scope. Take it out of there Commented Mar 12, 2015 at 16:31

2 Answers 2

3

readCookie is undefined because readCookie is not global; it is visible only within the document.ready function scope in mymy.js.

Make the function global by removing the document.ready wrapper.

Sign up to request clarification or add additional context in comments.

1 Comment

It might be good to also mention that it might not have been executed, too.
1

From the docs:

The callback is fired once the script has been loaded but not necessarily executed.

In other words, you cannot rely on the success function to be called explicitly after the loaded script is executed, e.g., its functions put into the global scope.


After your edit (which IMO should have been what you posted first) you actually have two issues; as written it's scoped only inside JQ's DOM-ready function.)

1 Comment

Interestingly, that text now says "The callback is fired once the script has been loaded and executed."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.