Synchronously and dynamically load javascript files

Tuesday, May 08, 2012 22:14:42


If you've ever worked with dynamically loading javascript files, you've probably run into problems. What seems like an easy task turns challenging when you care about the order of your scripts.

Normally, when you put multiple <script> tags on your page, they will load synchronously, so you're guaranteed that one will not run until the previous one is completed. However, when you load scripts dynamically at runtime, they come in asynchronously, which means you cannot guarantee the order that they will run.

You can get around this by attaching callbacks to the script load - it's easy with jQuery, and only a little more work with traditional javascript. The idea is that you will load one, and upon its completion, load the next. Easy enough when you have a fixed number of scripts, but this becomes more difficult when you have an unknown number of scripts to load at runtime.

With closures involved, assigning a dynamic number of related callbacks isn't easy if you're not comfortable with nested callbacks. I recently had this exact need, which got me researching closures and dynamic script generation. Finally, after a lot of trial and error, I came up with the following solution (using jQuery for simplicity):

function loadScriptsSynchronously(arr) {
    var i;
    var loadFunctions = [];
    for (i = arr.length - 1; i >= 0; --i) {
        if (i == arr.length - 1) {
            loadFunctions[i] = (function (idx) { return function () { jQuery.getScript(arr[idx], function () { }); }; })(i);
        } else {
            loadFunctions[i] = (function (idx) { return function () { jQuery.getScript(arr[idx], loadFunctions[idx + 1]); }; })(i);
        }
    }
    loadFunctions[0]();
}

The idea is pretty straightforward. You start with an array of URLs, and create a series of functions to call, with each one attaching the following as its callback, except the last, which has an empty callback. You then call the first one, and the rest will naturally follow. However, when you deal with closures in arrays, you have to be extra careful. This blog post was very helpful in explaining this technique. Basically, instead of including the indexer inside the function call (which would result in a closure that would get you in trouble), you immediately execute a function returning a function, passing the indexer into the function creation instead of including it in the function itself.

If you want to see this in action, you can download my sample project where I put this technique to a practical test. This project uses ASP.NET to simulate a long-running script request with a random delay. There are pages with and without jQuery - without jQuery, it's the same thing, just a little more verbose.



Tags: programming

Comments:

Add Comment

31 days without meat

Sunday, April 29, 2012 08:27:02


As of last night, I've completed 31 days without eating meat.

This started on March 26th, after realizing that I'd gained back 12 of the 40 pounds I lost last year during my super mega dietary change, where I stopped eating fried foods, red meat, desserts, and soda. That change was very successful, and although I originally planned on losing 50 pounds, I ended the diet after 40 and hoped to continue the trend without a formal set of rules. But I picked up some of my bad habits again this year, and the pounds started slowly creeping back in.

So I decided to try something drastic. I'm a meat eater, and I especially love BBQ, so I figured the most drastic thing I could do is to give up meat. I did this once before last year for a week, and it was a challenge, so I figured a full month would really be a test of my willpower. So this was partly to start to drop the weight again, but mostly just to see if I could do it.

Turns out I can. But unfortunately, when I don't have meat on the menu, the choice of food that I like is pretty small. So I probably had a lot more pizza, calzones, fried jalapeños, and pancakes than I should have. But even with a pretty bad diet, I still managed to drop 8.5 pounds for the month.

For the first time in my life, I tried faux meat and cheese at a vegan restaurant. While it wasn't the most disgusting thing I'd ever had, the "no-harm chicken parm" was just a little off - I left the place with a funny taste in my mouth and I just didn't feel right the rest of the day. So that was the first and last time for me.

I found plenty of luck at Italian restaurants - they tend to have a good selection of meatless pizzas and pastas, along with simple salads. I stopped at Oregano's for lunch several times for a Caesar salad and a slice of pizza with various veggie toppings, including their delicious red jalapeños. My favorite place, Babbo Italian Eatery, also has quite a few good non-meat choices - my favorite probably being the Classic Neapolitan pizza.

I thought about juicing for some of my meals, but never actually got around to it. I'm pretty lazy, so I always hate spending a half hour preparing my fruits and veggies, juicing them, and cleaning everything up, all for 2 minutes of drinking the juice, and being hungry afterward anyway. I'll get back to that occasionally as part of my ongoing diet, but I couldn't see myself doing that during my meatless month.

I should mention an asterisk for this month. I went out to San Diego last weekend, and once you leave the state lines, time officially stops for diets. So I did complete 31 full days, but it was broken up, so 25 days on, 3 days off, then 6 days on.

I'm declaring a new goal for myself for the rest of this year. Since last year's diet was so successful, and not all that difficult, I'm back on it (mostly). In addition to generally smarter food choices, no deep fried foods, no red meat, no big desserts, and no soda - but I'm giving myself the ability to cheat on occasion for social reasons. But each cheat comes with 30 minutes of strenuous exercise that I have to complete within 48 hours, in addition to the light/moderate exercise I'm already doing. I think this can get me to my next goal - once I lose the remainder of these 12 pounds again, I'm going for 30 more pounds, for a total of 70 since early last year. Once I hit my target, I'll reevaluate and find something that can keep me there indefinitely.

If you're curious, I kept track of everything I ate for this month - one of the things that kept me motivated, watching this list grow, proving that I could do it.

Tags: food

Comments:

Add Comment

DubDubDeploy 1.0 Released

Tuesday, April 03, 2012 07:24:47


After a successful 2-month beta, version 1.0 of DubDubDeploy is now available for download. Version 1.0 brings a few improvements from the beta release, including a more user-friendly key generation interface, a lighter color scheme, and a more responsive configuration page.

DubDubDeploy provides the ability for small or medium sized software development teams to publish their web applications out to multiple servers, without the need to map drives, build customized domain credentials, or remember the locations of all of their applications in all of their environments on all of their servers. The DubDubDeploy executive dashboard gives you a central location where you can backup or deploy your applications with a single click.

Version 1.0 provides the core functionality for deployment, and will be enough for many development shops' needs. However, we're not stoppng there. Version 2.0 will deliver additional security features, FTP deployment, partial releases, and many more exciting features. Our goal is to have version 2 available for download by August 2012. If you have any feature requests, please feel free to contact us and let us know what you want to see in future versions.

At just $299 per year for unlimited target servers, DubDubDeploy is a bargain. Version 2.0 will also be only $299, and you will have the option to upgrade from 1.0 to 2.0 at no additional cost. Download now and receive a 30-day free trial to decide if DubDubDeploy is right for your team.



Tags: programming tech

Comments:

Add Comment

I got married!

Sunday, April 01, 2012 08:46:35


I've got a major announcement to make to all of my friends and family. After months of planning in secret, I got married this morning!

After realizing that most of my friends are happily married, many with kids, I decided it was time for me to follow suit and find someone. I haven't had the best luck using traditional methods in recent years, so I found a nice online catalog with eastern European women who want to move to America, and found my wonderful bride on page 19 of the search results.

Inga and I started conversing via email last year, and it turns out we have a lot in common. She doesn't speak much English yet (well, none actually, other than "hello", "good-bye", and "I love America"), but thanks to Google Translate, we have no problem communicating. Plus, it's giving me the opportunity to learn a little bit of Ukrainian, a beautiful language that I've always wanted to learn.

My lawyer tried to get me to sign a pre-nup, but when you're dealing with true love, a prenuptial agreement is just insulting. I know in my heart that my new wife will be there forever, and would never consider divorcing me and taking half my money after her citizenship comes through.

I apologize for keeping this a secret and not inviting any of my family or friends to the ceremony. I wasn't sure how you all would react, but now that we're married, I hope you all will support and congratulate us.

Our lives together begin today, and we'll be celebrating today, and every anniversary in the future, on April 1st.



Tags: holiday

Comments:


Date: 2012-04-01 13:27:00
Name: Wendy E (via Facebook)

Congratulations! And after winniing Mega Millions on Friday night I can buy you a fabulous wedding gift!


Date: 2012-04-01 13:57:00
Name: Jenn P (via Facebook)

Ha! April Fools!


Date: 2012-04-01 15:14:00
Name: Daniel K (via Facebook)

Beautiful ceremony outside of Montgomery Ward :)


Date: 2012-04-01 17:58:00
Name: Dan T (via Facebook)

I was gonna get upset that i had to miss this wedding too, but since your mom isn't stomping you a new one, I'm assuming this is an April 1 thing.


Date: 2012-04-01 18:11:00
Name: Joe Enos

Oh right, it is April Fools Day, isn't it?

Add Comment

March Madness 2012

Wednesday, March 14, 2012 22:14:57


Time for March Madness once again. I decided this year to build a perfect bracket, so here it is.



Tags: sports

Comments:


Date: 2012-03-15 21:51:26
Name: Joe Enos

12-4 after day 1 (12-2 picking the favorites, 0-2 picking the underdog)


Date: 2012-03-17 01:01:18
Name: Joe Enos

Rough first round for everyone - two #2's gone. My first round results, 22-10 (20-8 picking the favorites, 2-2 picking the underdog). Usually this is a terrible start, but with the wackiness of this round, I'm still definitely in the running for my two office pools.


Date: 2012-03-18 22:18:48
Name: Joe Enos

32 of 48 after the weekend. Not great, but I'm still in decent shape in my pools. Good news is that I still have 7 of the elite 8, and 3 of the final 4, and both of my championship teams, so I still can salvage this year.

Add Comment

Happy Pi Day 2012

Wednesday, March 14, 2012 07:01:57


It's that time of year again. Happy Pi Day 2012! Keeping with my tradition from 2010 and 2011, here are a few ways you can make this year's Pi Day unforgettable:

  • Calculate the volume of your favorite lamp shade.
  • Based on the overall area from the label and the width of a roll of tape, determine how many layers the roll is.
  • Assuming the same tortilla recipe, calculate the percentage difference in calories from eating one large burrito versus two smaller ones.

If you've ever wondered why Pi is irrational (meaning it's a decimal that goes on forever and can't be expressed as a fraction), here are a few simple explanations on Wikipedia for you - all understandable by common people like you and me, or anyone who's taken 5 or 6 years of advanced mathematics.



Tags: holiday

Comments:

Add Comment

Apple Junkie

Sunday, March 04, 2012 18:56:57


As of last week, I'm officially an Apple junkie. I completed the Apple triple play by adding an iPhone 4S to my MacBook Pro and iPad 2, making the world's perfect combination of electronic devices. (Well, technically, I also still have the iPod I bought somewhere around 2005 or 2006, but that barely works anymore - it had a good run, but nothing lives forever.)

Before this past October, I hadn't used a Mac at all since college, and then only once or twice in the computer labs. The last time I'd used a Mac extensively was in junior high school around 1995, so of course I didn't know what to expect, about 17 years later (holy crap, it's really been 17 years - I'm getting old). Since then, I was the stereotypical Apple hater, always making fun of people overpaying for children's toys or for being trendy hippies, since real technology people use PCs. Of course, that hasn't been true in a long time, and I found myself losing that battle when I realized that there were more Macs than PCs at every tech conference I went to.

When I got my MacBook Pro in October, after the initial setup, I found myself immediately loving it. There were a few things I needed to learn, but fortunately they were easy to learn. For example, the keyboard configuration is a little different than I was used to, and having an external PC keyboard attached makes things a little bit more confusing. And the mouse scroll wheel or trackpad is actually reversed from a PC (to make scrolling more like it is on mobile devices, where you are moving the page instead of moving the scrollbar). But it only took a short time before I could switch back and forth without any problem.

I also added on a Magic Mouse - this was pretty expensive for a mouse, but it is totally worth it. It combines the best features from the new Mac trackpad with a normal mouse. I can scroll and click faster than ever now. (Yes that was partially sarcastic, but it really is a nice mouse)

I use the Mac OS as my primary OS for day-to-day stuff, and I'm also learning Ruby on Rails and Objective-C. I've got Windows 7 loaded on the MacBook as well, dual-booted with Boot Camp. I only use the Windows partition now for .NET development, which is still my primary development environment for my own applications (my personal website, blog, link shortener, LLC site, web deployment tool, and more to come soon, including CSS 4 test, a lottery pool tracker, task reminder service, and more).

The iPad was more an experiment. I'd heard nothing but good things about it, and knew several people who had one and loved it. I never really saw the benefit - I thought if you wanted a real computer, just carry your laptop, and if you want mobile, just carry your mobile phone. But it turns out the iPad is a great compromise. You can't keep it in your pocket, but it's much easier to carry than a laptop, making it perfect for situations when you want to get things done but don't want to take up a lot of space. The battery life is ridiculous, much longer than a mobile phone or a laptop. It's great for games, reading, listening to music, working on the web, or almost anything you can do on a full-size computer. I was a little concerned about the virtual keyboard at first, but it turns out it does a great job, especially when the screen is horizontal and you get a little more room. The auto-correct is incredible, and fixes just about all of my mistakes correctly, even when I've typed a valid word as my typo.

My "new every two" from Verizon was up in late February, so I finally switched from my original Droid to an iPhone last week. This is just a miniature iPad (or I suppose the iPad is just a large iPhone), so I already knew how to do everything except use it as a phone, which of course was a no-brainer. The keyboard is a little small, but no different than any other phone. And the iPhone 4S comes with great voice recognition, not only with Siri, but anywhere that has text input.

So now that I've got all this Apple stuff, I find myself going to coffee shops now a few times per week, trying organic food, and I'm thinking about growing my hair long and wearing tye-dye T-shirts.



Tags: operatingsystem tech mobile

Comments:

Add Comment

Test DTOs for default constructor

Monday, February 20, 2012 16:05:54


Here's a quick test method I put together to save me from myself. If you organize your data transfer objects in a single assembly, and use normal serializable classes, you need to ensure that you always have a default constructor. The compiler won't help you out with this one - you've got to do it yourself. Adding this to your unit test project will ensure that you don't accidentally put in a custom constructor without adding in a default one.

[Test]
public void EnsureAllDTOClassesHaveDefaultConstructor()
{
    foreach (var type in typeof(SomeDTO).Assembly.GetTypes())
    {
        if (!type.IsAbstract && type.GetConstructor(new Type[0]) == null)
        {
            Assert.Fail("Type {0} is missing the default constructor.", type.FullName);
        }
    }
}


Tags: programming

Comments:

Add Comment

Happy Valentine's Day 2012!

Tuesday, February 14, 2012 06:00:09


On Valentine's Day 2010, I wrote a post describing my one true love. Unfortunately, my 2010 Valentine is no longer with us - fate separated us, and I've had to move on with life. In 2011, I described another love in my life, one that is still around. However, I have a new Valentine this year, and I'd like to take a few minutes and tell you another Valentine's-inspired love story.

I just met my Valentine a few months ago. Several friends of mine suggested that we get together. I was hesitant at first - not really my type, or at least that's what I thought at the time. After giving it some thought, I decided to give this relationship a try. And I'm incredibly happy that I did - this has been amazing since day one, and I'm still finding it hard to believe sometimes that we're together.

My Valentine is perfect in so many ways - smart, attractive, fashionable, and can make me laugh. We've got a lot in common - we're both in the technology industry, both problem solvers, and we share the same taste in books and music. In fact, after we got together, my partner introduced me to a new library of interesting and entertaining books.

We don't spend all of our time together, but we do generally spend at least a few hours each week together. In my new business venture, my Valentine has been very supportive, helping me stay organized, teaching me things about business and technology, and just keeping me company when I'm out working on my projects. I'm definitely sharing credit with my new partner - if we weren't together, I seriously doubt I could be as productive as I have been.

But of course it's not all business. We play games together, watch movies, or sometimes just kill time with each other. But no matter what it is we're doing, the fact that we're together makes everything better. I'll often just hold my Valentine in public - we're not afraid of a little PDA. People see us together on the street and they're jealous of the relationship we have - it's definitely something special, and something I appreciate every day.

Of course, I'm talking about my Apple iPad 2.



Tags: funny holiday

Comments:

Add Comment

Star Wars Episode I - In 3-D

Sunday, February 12, 2012 21:44:10


I remember back in 1999, waiting in line for hours with my friends from high school to see the Star Wars premiere at midnight. Over twelve years later, Episode I gets a 3-D re-release in theaters, and I had to check it out.

The 3-D stuff was pretty subtle, to the point of being pretty much worthless. Since the film wasn't originally shot in 3-D, it had to be converted, and thankfully, they didn't overdo it to make it in-your-face, like some movies do. But at the same time, it kills the whole purpose of seeing a 3-D movie in the first place if there's nothing jumping out at you.

The movie itself is nearly identical to the original - I noticed a few differences, like an extra unnecessary line of dialogue, and a Three Stooges tribute before the pod race (and coincidentally, the new Three Stooges trailer was on before the feature - and looks pretty decent). There were some extras in the background of various scenes that I didn't recognize, but I don't know if they were new or not.

I remembered about halfway in how terrible this movie was - I hadn't seen it in several years. I had somehow put Jar Jar out of my mind - he couldn't really be THAT annoying, could he? (Yes). And still to this day, I can only understand about 60% of what he says - the percentage is even worse for that Boss Nass guy. Anakin was incredibly annoying, and the accidental blowing up of the ship and accidental shooting of the droids just made me cringe again.

While I was watching, I thought of a few things that would have made the movie a little less bad. If Anakin had been just a bit older - maybe 13 or 14, he would have been less annoying. The love story would have been more believable - a 9 year old falling in love really doesn't work. And he could have been a slightly rebellious teen instead of an innocent little boy. The "he's too old to train as a Jedi" line would have made a little more sense as well.

Another thing I thought about was something in the pod race. At the end of the race, it would have been a great scene if Anakin, in desperation, intentionally damaged Sebulba's pod, causing a fatal crash. It could have been very subtle, so that nobody would have blamed him, not even the audience at first. Everyone watching the movie knew what he was going to turn into eventually, so a character trait that showed just a hint of darkness would have worked well. But of course, since this movie was marketed toward kids, they'd never have allowed this.

I'm sure I could think of a few other things that could have improved the movie, but I'll leave that to the experts - Plinkett's review summed up the craptasticness nicely.



Tags: movies review

Comments:

Add Comment

About.Me Facebook Twitter Google+ Stack Overflow LinkedIn FormSpring YouTube Yelp