Friday, July 25, 2014

SharePoint 2010: Fix jQuery error: “undefined is not a function” in Safari

SharePoint 2010 can be a funny animal sometimes. If we throw Safari, web parts and jQuery into the mix, then we are in for a real barn burner. This blog entry discusses a problem I ran into where jQuery wasn’t initializing properly and a solution to the problem. Specifically, jQuery version 1.11.1 wasn’t initializing when I was using Safari 5.1 and was on a page that included an Excel Web Access web part. The solution uses conditional comments in the master page to select the correct version of jQuery based on the user’s browser.

Jump to Section



1. The Problem

I was testing my SharePoint 2010 branding efforts in Safari 5.1 when I came across the bug shown in Figure 1. The error reads “TypeError: ‘undefined’ is not a function (evaluating ‘b.cloneNode(!0).click()’). This signifies that there is some code in jquery.min.js that isn’t working. The error occurs in Safari 5.1 when I import the jquery.min.js library on SharePoint 2010 pages with an Excel Web Access web part. I was using jQuery 1.11.1 because it was the newest version of jQuery that supported older versions of Internet Explorer. I later determined that jQuery 1.11.1 doesn’t play nicely with SharePoint in this specific scenario.

Figure 1



2. The Solution

I waged war with jQuery versions until I discovered that this bug doesn’t occur when using jQuery 1.8.0. I could simply use jQuery 1.8.0 for all browsers, but that didn’t sit well with me. I want to use the most up to date working version of jQuery possible for each browser. That meant using 1.11.1 for Internet Explorer and 1.8.0 for all other browsers. I accomplished this by using conditional comments to reference my jQuery scripts. Figure 2 shows the original code that I had to reference jQuery script. Figure 3 shows the code containing conditional comments that I replaced it with.

  

Figure 2



In Figure 3 the first line tests to see if our browser is Internet Explorer. If it is, then we import the jQuery library 1.11.1 from Google’s API library. The second line in Figure 3 says that if our browser is not Internet Explorer, then we import the jQuery library version 1.8.0 from Google’s API library. The result of these conditional comments is that we use a working version of jQuery based on the browser we are using.

  
    

Figure 3



3. The End

You probably won’t see jQuery breaking often unless it’s an extreme edge case like the one detailed in this blog. Filtering scripts and cascading style sheets using conditional comments helps a lot with supporting different browsers. We took that idea and applied it by ensuring that our SharePoint 2010 site supports the most up-to-date working version of jQuery possible based on the users browser.