CAT | Uncategorized
The other day I had to alter the stylesheets in a child IFrame when a user selected an item from a drop-down. My first draft was pretty ugly, it ivolved getting the DOM from the child IFrame (by getting it’s contentWindow or contentDocument property) then getting the
of the DOM and looping over all the child items… yuck!I coded up this jQuery extension method which will return a jQuery-wrapped DOM instance for any of the matched IFrames.
(function($) {
$.fn.extend({
dom: function () {
var $this = $(this);
var getDom = function(o) {
if( !o || (!o.contentWindow && !o.contentDocument) ) {
return null;
}
var doc = (o.contentWindow || o.contentDocument);
return doc.document || doc;
};
var dom = getDom($this[0]);
return dom === null ? $this : $(dom);
}
});
})(jQuery);
So with this, getting the styles for a child IFrame is as easy as:
$('iframe').dom().find('head link').each(function(index, item) {
alert(item.href);
});
Unfortunately, this code will only work if your IFrame is hosting content that is on the same domain as its parent.
13
Solving “$(document).ready is not a function” and other problems
6 Comments · Posted by Jared
Has this ever happened to you: you’ve been working on a customer’s site, writing some really awesome jQuery flashy, fadey, scrolly, interactivey thing, you deploy it, and everything is awesome. The customer rejoices and the customer’s customers rejoice. Rejoicing is had by everyone.
And then you get an email one day:
“Everything is broken. We’ve kidnapped your dog. Fix our site or you’ll never see Spartacus again.”
And before you have time to wonder why you ever named your dog “Spartacus” to begin with (i mean come. on.), you’re off in debug hell. You load the site and see all sorts of weird errors:
“$().ready is not a function”
“$(document) doesn’t support this property or method”
Or my personal favorite:
“null is null or not an object”
You open up FireFox, activate FireBug, load the console, and type “alert($)”, press run, and instead of seeing the expected jQuery function:
function (E, F) {
return new (o.fn.init)(E, F);
}
You instead get:
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++) {
elements.push($(arguments[i]));
}
return elements;
}
if (Object.isString(element)) {
element = document.getElementById(element);
}
return Element.extend(element);
}
Or even:
function $(id) {
return document.getElementById(id);
}
DOH! Looks like another javascript library has been loaded and has overwritten the $() shortcut for jQuery. Woe is I. Why can’t we all just get along?!?
Well, we can’t stop people from including their favorite javascript libraries, but what we can do is prevent our code from suffering as a result. We’ll need a nice, big beefy, bodyguard to make sure our code isn’t messed with while it’s out clubbing with Prototype, Scriptaculous or even MooTools (who invited him??!?).
Here’s what our bodyguard function will look like
( function($) {
} ) ( jQuery );
So what this does is call our anonymous function and pass the jQuery object. This will scope ‘$’ to within our little function so we won’t step on anyone else’s toes (and they won’t bump into us while we’re on the dance floor and spill our drink everywhere). Okay, I think I've taken the clubbing metaphor far enough.
Basically this will allow our code to run and use the $ shortcut for JQuery as if it were loaded without any of these other libraries on the page.
Here is what the completed code would look like:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js" type="text/javascript">
</script>
<script type="text/javascript">
( function($) {
// we can now rely on $ within the safety of our “bodyguard” function
$(document).ready( function() { alert("nyah nyah! I’m able to use '$'!!!!"); } );
} ) ( jQuery );
//this will fail
$(document).ready( function() { alert('fail?'); } );
</script>
I love using this simple self-calling anonymous function style when working with jQuery because it saves me from typing jQuery(), which really does look a lot more ugly than using the $() shortcut. It also protects my code from any scoping issues and lets the code function normally when jQuery is put into no conflict mode.
My opinion, if you're doing work in jQuery on sites that you don't control 100%, you should be using this method to protect your code and your clients.
Updated: changed link for jquery to use 1.4.1 at the google CDN (tsk, tsk, tsk I was using the googlecode.com link)
I’ve spent the last few days going over what I want to accomplish this year, what I think I definitely could do, what might challenge me and what is just this side of impossible. Whenever I’ve made my resolutions known in the past its always been in a passing conversation with a friend of family member. I never wrote them down or tried to keep track of them once the conversation was over so this year I decided to post them publicly to give me that extra bit of motivation, and also I’ll be able to check back here throughout the year and see how I’m measuring up.
These are in no particular order.
I need to grow more as a professional. Last year I went to my first conference (MSDEVCON) and it was a total blast. I met a lot of truly awesome and intelligent people and learned a billion things that I didn’t know before. After that I attended Stack Overflows Dev Days in Boston and it was the same experience all over again. This year My goal is to start attending more conferences/events (as many as I can afford with time and $$$) to grow myself as a professional.
Make more mistakes. I made my fair share of mistakes in 2009 and (more importantly) I learned a lot from them: about myself, my skills, and what I am capable of. I’m addicted. I’m going to put myself more out in the open and make some more mistakes so I can learn a lot more in 2010.
I need to lose at least 25lbs this year. I’ve let myself go over the past few years and it’s time to take my health more seriously. 25lbs probably doesn’t sound like a lot and honestly it’s a lot less than I need to lose but I’ve never been good at staying fit so hopefully I achieve this goal relatively early and am able to keep the weight off the rest of the year.
No more sugary drinks, especially soda. I’m looking at you Mt. Dew. I’m not sure what happened but between the end of the year work rush and the holiday (fr)antics I’ve been downing soda like it’s going out of style. Time for that to end.
Eliminate debt. This goal is a bit lofty but my goal is to eliminate 80% of all my debts this year. This is going to be a tough one to pull off, what with the recent job change and our new house but it’s needed.
Finish something. I started way too many side projects last year, and I finished… none. Not one project I started in 2009 saw what I would call a 1.0 release. Time to crap or get off the pot. I aim to crap. My goal will be to promote at least 2 of the projects I started in 2009 to a 1.0 release this year.
More play. Tamara and I didn’t get a vacation last year and we are dying for some time away. This is going to be tough with all my debt elimination going on but the more debt I get rid of the more I can save.
More sleep. Tamara reminds me all the time how little sleep I get ( about 4-5 hours a night at most ) and it really started to show during the holidays. I simply ran myself into the ground. Time to recharge and see what I can really do.
No tags
I’ve wrapped up work on v0.4 of the Jsoq Console, and the insanely strenuous release cycle for v0.1 of WhatDidIJustEat.com so I’m starting another side project tonight.
Ever been working with a programming language you’re not 100% familiar with and find yourself wondering:
Is this function a built-in function or in some included library?
What assembly is this class in again?
Can I name my class XXXX without conflicting with another class?
I’ve had these questions recently and found myself annoyed and frustrated to no end (PHP, I’m looking at you) so I’ve decided to build a system to keep track of this stuff for me :D.
The first thing on my list (because it was the easiest) was to do a data dump of all the public classes in the .Net Framework, including the ones in my GAC, and store some metadata for each one in a database table. I’ve just finished this step and thought that this data might be useful, so I’m posting it here.
Currently the fields included in the data dump are:
[namespace] = The namespace that the class exists in (ex: System.Collections.Generic)
[class_name] = The name of the class (ex: StringBuilder)
[assembly_fullname] = The display name of the assembly (ex: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
[assembly_file] = The full file path to the assembly (ex: C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll)
[framework_name] = The framework that uses this class, for this dump they will all be 'Microsoft .Net'
[framework_version] = The framework version that uses this class (ex: v.2.0.50727)
The .sql file takes about 18 seconds to run to completion on my AMD Athlon X2 2.53ghz machine with 4gb of RAM.
If you’re curious about how I generated the .sql file, below is the code I used to find all the classes. It’s not pretty but then again it was just meant to get the data into the database. Just paste the code into a new console app and run it in a command window like so:
[application_name].exe > c:\classes.sql
Or, you can download the .sql file I’ve generated (it will also create the table you need to store the data).
static void Main(string[] args)
{
var dictionary = new Dictionary(){
{ "v2.0.50727", @"C:\Windows\Microsoft.NET\Framework\v2.0.50727" },
{ "v3.0", @"C:\Windows\Microsoft.NET\Framework\v3.0" },
{ "v3.5", @"C:\Windows\Microsoft.NET\Framework\v3.5" },
{ "v???", @"c:\windows\assembly\gac" }
};
var types = new List();
foreach (var pair in dictionary)
{
var path = pair.Value;
var assemblies = Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories);
foreach (string file in assemblies)
{
try
{
Assembly asm = Assembly.LoadFile(file);
foreach (Type t in asm.GetTypes())
{
if (t.IsPublic)
{
Console.WriteLine(String.Format(
"INSERT INTO Classes (" +
"[namespace], " +
"class_name, " +
"assembly_fullname, " +
"assembly_file, " +
"framework_name, " +
"framework_version" +
") " +
"VALUES (" +
"'{0}', " +
"'{1}', " +
"'{2}', " +
"'{3}', " +
"'Microsoft .Net', " +
"'{4}'" +
")",
String.IsNullOrEmpty(t.Namespace) ?
"GLOBAL" :
t.Namespace,
t.Name
.Replace("`1", "")
.Replace("`2", "")
.Replace("`3", ""),
t.Assembly.FullName,
t.Assembly.Location,
pair.Key == "v???" ?
t.Assembly.GetName().Version.ToString() :
pair.Key
));
}
}
}
catch { }
}
}
}
If you found this useful, let me know in the comments!
.NET · Open Source · Programming · SQL
Being an uber geek means many things. Late-night code-a-thons just-because, intense debates about zombies vs. pirates vs ninjas (zombies ftw!) or Greedo shooting first, and a desire to have everything running as fast and efficiently as possible.
If you agree with that last sentiment, and you follow everything Google does then you’re probably wondering if Google’s new plans to eventually dominate the entire internet free domain name server lookup service is going to offer you any performance benefits. Well I was wondering the same thing and here is how I determined that it was a good idea to switch.
- Download the DNS Performance Test application, extract the zip archive to a folder on your system and run the executable
- The app will start and randomize it’s list of URLs. After this is done just click start and switch to the Stats tab
- I let the app run for ~500 results to get a good sample of data. After you’re satisfied with the number of results click the stop button and note the “Average Query Time”
- Follow Googles directions for switching your DNS over and then repeat steps 1-3 above
After I did those steps I had an average of 213ms for my ISPs DNS and 190ms for Googles. So in my case Google is definitely faster; a 12% increase in DNS lookup performance. So it looks like I’ll be switching over. As for you, well, your mileage may vary.
Did you switch to google? Stay with your current provider? Or maybe you went with OpenDNS? Let me know how it worked out for you in the comments.
