Monthly Archives: April 2016

Javascript function to check JQuery loaded or not

I was working on a project in ASP.Net MVC today. The application needed to invoke JQuery calls on document load event. While the code was working mostly fine, there was one issue where IE was throwing an error message “JavaScript runtime error: ‘$’ is undefined” at random intervals.

While troubleshooting, I had some insight on what the issue was. IE was unable to understand the $ symbol, which means JQuery was not loaded fully. To avoid these kind of issues in future, I have come up with the below solution written in javascript code to check whether the JQuery was loaded at the client side before invoking the calls on DOM events.

This was the culprit buggy script (I was trying to apply some JQuery animation on #welcome-message):

$(function() 
  {  
    var message = 'Welcome, someUserName!';
    $("#welcome-message").html(message).hide().show('slow');
  });

This was my solution:

    function checkJQuery() {
        //Check jQuery object is loaded
        if (typeof(jQuery) == 'undefined') 
        {
            setTimeout("checkJQuery()", 30);
        } else {
                        
            $(function() {  
                var message = 'Welcome, someUserName!';
                $("#welcome-message").html(message).hide().show('slow');
            });
        }
            
    }
    checkJQuery();