views:

43

answers:

2

I want to render specific HTML in a partial view based on whether javascript is enabled or not. My idea was to some how detect whether javascript was enabled and store it in a session variable which I can then test for in my view e.g.

<div class="product">
<%
    // if Javascript is enabled, load the images asynchrously, otherwise load them directly.
    string imgHtml = "<img id=\"myImage\" src=\"{0}\" alt=\"MyImage\" />";
    if ((bool)Session["jsEnabled"])
       imgHtml = String.Format(imgHtml, Url.Content("~/Content/images/ajax-loader.gif") + "\" onload=\"loadImageAsync(this, '" + Url.Content("~/Content/images/" + Model.thumbnail) + "')");
   else
       imgHtml = String.Format(imgHtml, Url.Content("~/Content/images/image.jpg")); 
%>

    <div><%= imgHtml %></div>
</div>

From what I have read most seem to suggest using a hidden field and setting it's value in javascript, however, I don't quite understand how I can get this to work in MVC unless I post the data somewhere (this particular view isn't within a form).

A: 

Correct me if I'm wrong, but it looks like you are trying to use progressive enhancement. If that is the case, then the proper thing is to have the page render the most basic version (the .gif), and then attempt to have the more advanced technology (javascript) itself supersede/overwrite it with the more advanced (javascript) version.

ThatSteveGuy
What I am trying to do is have the image load asynchronously if JavaScript is enabled, otherwise load the image with the page. The normal images that are loaded are quite large jpegs (this partial view is what renders the image for each) so surely loading the basic HTML e.g. src="image.jpg", is going to nullify any performance increase?
James
A: 

You could use JavaScript to make an AJAX call to a method that sets the session variable. If JS isn't enabled then no call is made and no variable is set.

I would also pull all that code out into a helper method that just takes the src of the image as it'll make your views a lot cleaner.

Chao
@Chao: Couldn't there be the possibility that the ajax call doesn't complete before the page loads?
James
Yes there is the issue that the first page load will not have the session variable so the non-ajax images will show which will always be the case using this method, however, after that, for the length of the session, it will correctly use the AJAX method.Another approach maybe would be to have 2 different pages (one for AJAX one for no-script). Link to the no-script version but have a JS redirect at the top, this will execute before the browser gets to the IMG tags.
Chao