Quick jQuery hack to fix position:fixed toolbars in iPhone/iPad/iPod Touch
This is just a quick fix if your postion:fixed elements end up in weird places when your site is viewed on the iPhone, iPad, or iPod Touch.
Say you have a div with an id of "#footer" that you want to stay at the bottom of the page. If you set it's position to "fixed" and set the bottom to "0px". When viewed on an iPad, iPhone or iPod Touch, the footer may end up in the middle of your content if you have a long page.
-
//stick the footer at the bottom of the page if we're on an iPad/iPhone due to viewport/page bugs in mobile webkit
-
if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod')
-
{
-
$("#footer").css("position", "static");
-
};
Benchmarking a simple DOM based cloning template
Sara Chipps recently posted a simple DOM based clone template method she uses in one of her apps. "Easy HTML Templating with JQuery"
My template looks like this:
CODE:
<script id="ItemTemplate" type="text/html" <li class="item" value="|rowNumber|"> <input type=”text” id=”input|rowNumber|” /> </li> </script>
Now within my code I need to put a place holder where I want my HTML to go. I have my unordered list called url_list.CODE:
<ul id="url_list"></ul>Now, you see that most of my items look like this “|rowNumber|” I have a variable in my code called nextUniqueItemID (I believe in extremely descriptive variable names). Here is my “addItem” function.
JAVASCRIPT:
function addItem() { var list = $('#url_list'), items = list.find('li'); list.append($('#ItemTemplate’) .html().replace(/\|rowNumber\|/gi, nextUniqueItemID++)) }
The use of global variables aside (cough,cough),I looked at it and, having used something like this myself, thought that it would work find for data sets containing a very small number of items. The problem is these kinds of clone based templates are VERY slow compared to the templating engines that are available for various JavaScript libraries.
I happened to read a post by Brian Landau called "Benchmarking Javascript Templating Libraries" this morning and wondered just HOW MUCH slower is the naive template method than a good template library?
I grabbed the benchmarking code and modified it to run the new clone based template method.
-
var nextUniqueItemID = 0;
-
function addItem() {
-
var list = $('#url_list'),
-
items = list.find('li');
-
list.append($('#ItemTemplate').html().replace(/\|rowNumber\|/gi, nextUniqueItemID++));
-
};
-
-
$(document).ready(function(){
-
var output = $('#output');
-
$.benchmarks = {};
-
-
$.benchmarks.test_simple = function(){
-
addItem();
-
};
-
-
$.benchmarks.loop_test = function(){
-
for (var i=0; i <5; i++){
-
addItem();
-
}
-
};
-
-
// use these lines to run the benchmark tests in your browsers JS console
-
// $.benchmark(1000, '#simple_test', $.benchmarks.test_simple);
-
// $.benchmark(1000, '#loop_test', $.benchmarks.loop_test);
-
});
Since the template Sara provided contains an input tag you get a different benchmark if you run the simple_test and the loop_test separately after refreshing your browser. You can run the tests for yourself here, the loop test *may* cause your browser to give you a "script is running slow" message, hit continue as the loop will eventually end. You may also get different numbers if you run the tests in IE, Chrome, and Safari.
results: using FF 3.5.5
Simple Test: 1.71s
Loop test: 31.534s
When you consider that the slowest loop test using a template library was just around 4.5s, you get a better idea of just how slow this method is when you have an input in your template.
So that's fine, but it's known that dynamically adding text inputs is slow in just about every browser and the original tests don't use inputs at all, just divs. So let's modify the template and see what the results are.
-
<script id="ItemTemplate" type="text/html">
-
<div class="test"><h2>This is a test of |name|</h2><p>The homepage is <a href="|url|">|url|</a>.</p><p>The sources is: |source|</p></div>
-
</script>
I modified the addItem function to account for the new data. n.b. The data I'm using is static, if you wanted to use a data source you would just modify this method to take in your data parameters.
-
function addItem() {
-
var list = $('#url_list'),
-
items = list.find('li');
-
list.append($('#ItemTemplate').html()
-
.replace(/\|name\|/gi, "Clone template method")
-
.replace(/\|source\|/gi, "http://girldeveloper.com/waxing-dev/easy-html-templating-with-jquery/")
-
.replace(/\|url\|/gi, "http://girldeveloper.com/waxing-dev/easy-html-templating-with-jquery/"));
-
};
results using FF 3.5.5 - refresh between each test
simple test: 1.285s
loop test: 3.771
results using ff 3.5.5 with no refresh between tests
simple test: 1.434
loop test: 4.227
So that's looking a little bit better. Not too much slower than the template libraries.
So what do the template libraries give you? Well the replace method works find provides your data is escaped properly. But say instead of a url in the "source" replacement, you use a file path like "file:\\foodrive\source.txt". Well it still gets replaced, but the text looks like this "file:\foodrivesource.txt". So in addition to the replacement, you have to make sure your data is properly escaped. A lot of template libraries will do this for you. Also notice that the addItem method has to do a DOM lookup on every iteration of the loop to get the template. If you have a large DOM, this could impact the performance.
A new JavaScript CDN from Microsoft
Microsoft announced a new Content Delivery Network for their ASP.NET AJAX JavaScript libraries and jQuery. This means that instead of hosting those libraries on your server, you can just link to the versions on Microsofts server. I made a simple page that takes a querystring parameter (q=) and uses the ASP.NET AJAX dynamic templates to bind search results from a call to the Bing API.
The money lines in the source are the following:
-
<script type="text/javascript"
-
src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjax.debug.js"></script>
-
-
<script type="text/javascript"
-
src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxTemplates.js"></script>
These two lines tell the browser to load the MS AJAX scripts from the CDN. There are some security concerns around the fact that the files are served from the microsoft.com domain. Both Google and Yahoo serve there files from a separate, non-cookied domain (googleapis.com and yahooapis.com respectively). Hopefully, these fears will be unfounded.
On a side note, it is surprisingly easy to use the Bing API if you are familiar with script tag injection. The easiest way is to put an empty script tag in your page.
-
<script id="jsonResults" type="text/javascript"></script>
And then just create your Bing URL and set the script elements src attribute to the URL you created.
-
function MakeSearchRequest(searchPhrase)
-
{
-
var req = "http://api.bing.net/json.aspx?"
-
+ "AppId=" + YOUR API KEY GOES HERE
-
+ "&Query=" + searchPhrase
-
+ "&Sources=Web"
-
+ "&JsonType=callback"
-
+ "&JsonCallback=BuildResults";
-
-
$get("jsonResults").src = req;
-
};
ASP.NET MVC Tip – Return specific views for specific errors.
Earlier I had said to keep your controllers as thin as possible, that doesn't mean that they should necessarily just be two, or one, lines of code.
Take an instance where you are retrieving items from a web service in your controller. Let's say that you get a 404 error and your service will throw an exception telling you that the service can't be found. Take a look at this controller action
-
public ViewResult Item(string itemID)
-
{
-
Item item = MyWebServiceWrapper.GetItem(itemID);
-
return View("Item", item);
-
}
As it stands this action is pretty thin, but if an exception is thrown the user will be presented with either whatever custom error page you have defined in your web.config or the dreaded Yellow Screen of Death.(YSOD). You can wrap the call in a try-catch block and catch the exception. But rather than creating a generic errors page that will display any raw exception message, it's a much better idea to return an error specific view to your user with a friendly error message.
-
public ViewResult Item(string itemID)
-
{
-
try
-
{
-
Item item = MyWebServiceWrapper.GetItem(itemID);
-
return View("Item", item);
-
}
-
catch(ServiceCannotBeReachedException)
-
{
-
Item item = new Item(itemID);
-
return View("CannotRetrieveItem", item);
-
}
-
}
-
-
//The CannotReachService view has a line that looks like this
-
// "The item <%= Model.itemID %> can not be retrieved at this time. Please try again later"
-
// obviously this can be globalized/localized as needed.
This leads to a much "dumber" view and is a much better idea than modifying the "Item" view to display errors if something isn't right with the model or passing in special error parameters to the view. Let the view deal with the data it is meant to display and nothing else.
ASP.NET MVC tip – Don’t use the Content or Scripts directories for view specific files
ASP.NET MVC creates a default file structure for you when you create a new project. It includes a Scripts directory, which contains the MS AJAX and jQuery .js files, and a content directory, which contains a Master page and CSS files. I find this to be extremely cumbersome and it forces me to jump around a lot. Storing shared CSS and JavaScript files in those locations is fine in my opinion. But if you are using View specific CSS or JavaScript files, you should put them alongside your view page in the Views directory. This allows you to quickly find the file you want to work on.
ASP.NET MVC TIP – Keep your controllers and actions thin
When writing you controller actions, keep them short and sweet. Don't add a lot of actions and keep a close eye on the length of each action.
Whenever possible, I try to make my controller actions look something like this.
-
public ActionResult DoSomething()
-
{
-
MyModel model = MyService.GetModel();
-
return View("MyView",model);
-
}
-
//or
-
public ActionResult DoSomethingWithAKey(int myKey)
-
{
-
MyModel model = MyService.GetModel(myKey);
-
return View("MyView",model);
-
}
(1)
There are two reasons to do this:
1) It makes your controllers less complicated and easier to maintain. - You don't want to have to do a lot of debugging in your controllers. Chances are, if you have a lot of complicated logic in your controller actions, you are probably mixing concerns. Make sure that your controllers are only responsible for getting data from your models and figuring out what view to send to the client.
2) It makes testing easier. If all you are doing is getting a model and passing that model to a view, what do you really need to test? Maybe that the correct view is being returned.
(1) Of course I use more descriptive names than "myKey".
