Category Archives: Web Programming

Notes that discuss my html5, jquery, php, based web programming

jqueryWriteLessDoMore120213

$.ajax logging using Ajax Global Events. Re-factoring Single Page Web Application

Background on $.ajax logging using Ajax Global Events:  So I’ve moved from jQuery 1.4 to 1.9. I have some time to refactor my code to take advantage of some of the new features of 1.9 and to get ready for 1.10; the next jQuery release removes some of the deprecated methods.

For this round of coding, I am focusing on the $.ajax() method. In my present design, my single page web application makes REST calls for many of the UI menu items. For example, a click on the FILE->LOAD menu item triggers a function call to code that retrieves a file from my server. The basic pattern is like this:

// Start spinner
// start logging timer
$.ajax({"url":RestURI,
 "type":"GET",
 "dataType":"json",
 success: function(data) {
 // Do success stuff (parse, format and display)
 // stop logging timer, do logging
 // stop spinnger
 }, /* end success: */

 error: function (req, stat, err) {
 // Do error stuff
 // stop logging timer, do logging
 // stop spinner
 } /* end error: */
});

I have more than 7 code blocks that follow this pattern. Since the success/error/complete callback functions have been deprecated and I need to touch the code anyways, I thought I’d use the newish $.ajax() global events handlers  to clean up my code. The event handlers seem to be a useful place to put common pieces of code that really shouldn’t have been so liberally cut-and-pasted when I wrote the original code.

jQueryIcon120213For each of my ajax code blocks, I put a generous amount of logging in. Maybe this logging should only be needed when writing/debugging the code, but for me, since I spend so little dedicated time on this application, I wanted to keep verbose logging on always to make it real easy for me to debug.

$.ajax logging using Ajax Global Events

The following new block of code is doing my $.ajax logging using Ajax Global Events.

$(document).ajaxSend(function(evt, xhr, settings) {
 console.log(settings.type+" "+settings.url+" Sent");
 start = new Date().getTime();
 // Other logging
});
$(document).ajaxSuccess(function(evt, xhr, settings) {
 console.log(settings.type+" "+settings.url+" Success");
 // Other logging
});
$(document).ajaxError(function(evt, xhr, settings, exc) {
 console.log( settings.type+" "+settings.url+" Failed. "
 +xhr.status+"-"+xhr.statusText);
 // Other logging
});
$(document).ajaxComplete(function(evt, xhr, settings) {
 console.log(settings.type+" "+settings.url+" Complete");
 end = new Date().getTime();
 diff = end - start;
 // Other logging
});

As you can see, the ajaxSend/ajaxSuccess/ajaxError/ajaxComplete events are fired in sequence at the $.ajax() function executes and after the  .done(), .fail() and .compete() callbacks are executed.

The “Other logging” comment represents 2 or 3 lines of code where I put logging information into a user visible menu item (REPORTS->LOG) where I can see even more details without having to open the console window. For me, this effort is a nice clean out some of the logging stuff, to make the application logic a little more visible;  this clears up a bunch of clutter for me.

New-ish .done/.fail/.always Callbacks

Therefore, my $.ajax() code blocks are straighten out to follow the new done/fail/always callbacks. Here’s an example new $.ajax() code block:

// Start spinner
$.ajax({url:RestURI,
 type:"GET",
 dataType:"json"})
 .done( function(data, textStatus, jqXHR) {
 // Do success stuff
 }) /* end done: */

 .fail( function (jqXHR, textStatus, err) {
 // Do error stuff
 }) /* end fail */

 .always( function() {
 // stop spinner
 }); /* End always */

Some things to note: I still put the start/stop spinner function calls inline. I may move this to the global even handlers, but not yet.

Deferred Objects

Also, the done/fail/always call backs follow the new Deferred Object model. This will then let me setup some promise objects to let me address some of the async race conditions I have in my application.

For example, I have a case where I can run FILE->SAVE and then run REPORT->General and the report will produce results before the save was completed. I know how to fix this, but I was looking to use my new ajax code blocks architecture to get some practice with promise objects instead… for next time.

Code Snippets Causing Slow Website Load Time

Background on my Slow Website Load Time issue: I wrote a blog entry that described how I upgraded one of my web pages to use normalize.css (part of my migration to HTML5 Boilerplate 4.2). Normalize.css let me clean up my CSS nicely and helped teach me some discipline on CSS design. All good, but…

The blog posting took a crazy long time to load. I am used to WordPress blog pages being a little heavy and but this was too slow.

I had recently learned about the WebPageTest.org tool, and decided to use it to troubleshoot my issue. Other bloggers point to this website for workingSlow Website Load Time issuess. Here’s what the tool’s waterfall summary page  showed me:

Webpagetest17secBefore110713

 

The chart had lots of red lines: these are lines that reflect 404 error timeouts. I was surprised; the posting didn’t have any links to external content (that I knew of!). I clicked on the waterfall thumbnail and saw the following:
Webpagetest404err110713

 

The 404s are from style.css, normalize.css, main.css, and jquery-ui — huh? These are links in my code snippet!

My blog postings showed the before/after of my <head> section of my normalized web page. Here’s the after snippet:

HeadSection110713

 

 

So do web browsers resolve and fetch URLs embedded in <pre> sections? Really? (sorry to be ignorant about this, but I really didn’t think so). Yes a quick search of stackoverflow and I find that this questions has been asked and answered. When you have a <pre> block, you need to escape the < and > characters (&lt; and &gt;). Stackoverflow reference

So, I manually edited my code snippets to escape the angle brackets, and everything loaded much more quickly. The browser no longer tried to resolve the URLs.

Here’s the new WebPageTest.org thumbnail (no red lines!)
Webpagetest10secAfter110713

Oh, and while I was learning the WebPageTest.org tool, I found a bunch of other problems, which were much more obvious and easy to fix.

Updating to jQuery 1.9

Background on why I was Updating to jQuery 1.9:  For a number of reasons, I needed to update my website to a newer version of jQuery, jQuery 1.9. My site, designed in 2010 was started on v1.4 and had last been updated to 1.7 in 2011. I knew I had several out-of-date methods and expected to some debugging and troubleshooting. Well, in the end, it took me 6 hours spread over two days. It wasn’t really that bad, but since I don’t upgrade jQuery everyday, I had a little re-learning to go through.

For starters, I knew that v1.9 had deprecated many of its old methods. In fact, I learned from the upgrade web page, , that v1.9 comes with a special migration plug-in. I was pleased to see this and used this to address most all of my updating challenages.

For example, $.browser() method was deprecated. The migrate script reported this to me in the Chrome console, as follows:

Chrome console:

With a little digging, I was able to find that I was using an old version of blockUI. When I changed to the new version the warning message went away.

I also got the following warning messages related to type changing and the change to the andSelf() method:

Chrome console:

Again, it took a lot of digging, but I was able to isolate the problem to my tmpl.js script. I was using a really old version. I think with a little more skill on my part, I would better be able to use stack backtraces or some other Chrome tool to find these quicker, but this problem was hard for me to find.

Since I was also using an old version of jQuery-UI, I stumbled upon a couple of breakages triggered by curCSS:

Chrome console:

For some reason, also, the dialog() method wouldn’t display text in the “OK” button and it would always popup at 0.0 (upper left), so I upgraded to jQuery-ui v1.9.2.

One last thing for Updating to jQuery 1.9. I had to change all of my .live() events to .on(). The migration guide clearly covered this.

Here’s an example from my website:

//$('#journal input').live('keydown', function(evt) {
$(document).on('keydown','#journal input', function(evt) {

This was easy to do; I had to do it in 6 different place, and it worked the first time.

Updating to jQuery 1.9 was a little more painful than I would like, but feels good to get caught up.

Ok, now that I’ve converted to jQuery v1.9, I can try out some of the new things.

H5BPLogo

Add Normalize to my HTML5 CSS

As part of updating my website to HTML5 boilerplate 4.2, I am finally converting my CSS to use normalize.css.

My original index.html file used the following

<head>
...
    <link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.16.custom.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/screen.css">
...
</head>

where style.css borrowed heavily from a prior version of H5BP and most of my custom styles were in screen.css. To me, all of this worked, but I was delighted to follow H5BP’s lead and refactor my CSS to use normalize.css.

My new index.html file looks like this:

<head>
...
    <link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.16.custom.css">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">
...
</head>

where normalize.css is version v1.1.1 taken from the H5BP github repository. The main.css is the H5BP file with my custom CSS inserted at the designated spot (“Author’s custom styles” section).

So I didn’t trust that this work work very well. I have always been kludgy and I mostly hack together my CSS; I am happy to align with a framework like H5BP, but I wasn’t optimistic that this would be easy.

So, I took an intermediate step to Add Normalize to my HTML5 CSS by creating a temporary file called indexnormalize.html. In Chrome, I setup two tabs, one with my index.html and the other with my indexnormalize.html and I did side by side comparisons, liberally using the “Inspect Element” developer tool built into Chrome.

After about an hour, I was done. It wasn’t that bad. Here’s a summary of the tweaks that I had to make to my CSS:

Background color. My web page has a black background. I have been setting it using the body tag, and I should have been using the html tag. The comments in normalize explain why this is better and there’s a whole series of blog postings explaining why my prior design was clueless (at best). Reference: Understanding the HTML versus BODY Element in CSS 

/* Part of file main.css */
/* old: */
body {
 ...
 background-color: black;
}
---
/* new: */
body {
 ...
}
html {
 background: black;
}

Drop down menu padding. The way my drop down menus were defined, the normalize.css margin and padding mucked things up. Rather than redesigning my menus, I added some CSS to compensate.

In normalize.css the following tripped me up:

/* Part of file normalize.css */
ul {
 margin: 1em 0;
}
ul {
 padding: 0 0 0 40px;
}

To fix this, in my custom css I added:

/* Part of file main.css */
#page-bar {
 padding: 0 0 0 0px;
 margin: 0 0;
}

Nav tag. My menus use the nav tag and so does normalize.css. I had to also fix the margin and padding there, too

/* Part of file main.css */
nav ul {
 margin: 0;
 padding: 0;
}

Printing styles. Also, I had to go into a different section of main.css to edit in my print styles. In the section titled “Print Styles” I put the following at the very end:

/* Part of file main.css */
...
 tbody, tr, img { page-break-inside: avoid; }
 tbody { border: 1px solid #999; }
 #head, #foot { display: none; }
}