Efficiently reusing (poorly designed) JSON template for additional sites? - css

My supervisor just handed me a pile of JSON files from a freelancer which we are going to use to make multiple (similar) websites. Lucky me, I'll get to be the one updating the content and css for the different versions.
This is my first time working with JSON, so while I can't be sure that this is a poorly designed template, the fact that the css is very messy (in order to change the color of buttons throughout the site from yellow to orange, at least 15 different classes need to be adjusted, which seems to me to defeat the whole purpose of css...) doesn't give me hope.
I've brute-forced my way through the first two different sites, but since it looks like we'll be doing a lot more of them, I'm looking for ways to streamline the process (in particular making sure to change the content in all the places the content needs changing, which is a lot of files, with different content for different versions).
I'm personally old-school enough to like awk (well, that, and it's what I'm most used to programming in), so my backup plan is to just set up an awk/batch script or two which will take in a "these are the bits of info that go in these specific places" file and update all the relevant files. However, I'm sure there's a better way to do this, which is why I'm turning to y'all.
Is there anything that already exists for streamlining processes like these? Or a coding system/language that's well-suited to this project? A GUI which I can connect to bits of text that need changing?
Ideally, I'd like to set up something that even a monkey (or a non-caffeinated me) could use as often as needed. I'm already going to have to dive into the source code to clean it up (because, gasp, we might need to be able to have more than 5 people on the "our team" page, for example - without bad css/html workarounds), so making other tweaks that'll help with the content update process can happen en route.

I have recently used underscore to render templates from JSON. this is a front end tool, but you could automate it with some backend tools (a simple cURL or file_get_content in php will do).
Here is a link to a tutorial
your template will be a JavaScript template in your html file:
<div id="rendered"></div>
<script type="text/template" class="template">
<%- rc.listTitle %>
</script>
and in your JavaScript code you load:
<script type="text/javascript">
// When rending an underscore template, we want top-level
// variables to be referenced as part of an object. For
// technical reasons (scope-chain search), this speeds up
// rendering; however, more importantly, this also allows our
// templates to look / feel more like our server-side
// templates that use the rc (Request Context / Colletion) in
// order to render their markup.
_.templateSettings.variable = "rc";
// Grab the HTML out of our template tag and pre-compile it.
var template = _.template(
$( "script.template" ).html()
);
// Define our render data (to be put into the "rc" variable).
var templateData = {
listTitle: "Olympic Volleyball Players",
};
// Render the underscore template and inject it after the div rendered
// in our current DOM.
$( "#rendered" ).after(
template( templateData )
);
</script>

Related

jquery mobile 1.4.5 single-page template href querystring ajax

I am a newbie to JQM (I use 1.4.5) and my webapp (asp.net C# apache Cordova) contains many separate pages of .cshtml (single-page template) only. I am testing my webapp on a Samsung Galaxy Grand using Android 4.2.2
A.
I am not sure about my understanding of 'linking pages', even after reading all the JQM docs on this and also after reading up many, many posts on this topic about passing querystring values to another page; mainly because I find that ALMOST ALL the examples are directed towards providing answers for internal pages (Multi-Page template) within a single html page.
So I request some of you JQM experts to confirm or correct the following understanding of mine....
From the JQM docs I understood that
I could use in any link (e.g button), href="page2.cshtml?par1=1&par2=2"; and JQM will automatically use Ajax for this link to work.
I also understood that use of querystring is always allowed in such cases of different html pages of the same domain and it will work via Ajax automatically ; so long as the attr such as rel="external", data-ajax="false" etc. are not used in the same link.
but querystrings are not allowed in case of the internal pages (multi-page template) only....;
and if I need to use the above href to link to a page in another domain e.g. www.anotherdomain.com/page2.cshtml?par1=1&par2=2, then I need to use rel="external".
Are all my above points (that reflect my understanding) CORRECT? KIndly confirm ro please correct me ...
B.
In my app, I find that most of the links work according to my understanding as above, to connect to different pages in the same domain; and I assume it happens via Ajax. Is it correct? I am also able to use the querystring params in page2 ( i.e. To-Page).
But in one case, though it works, in the To-Page the Panel features do not operate correctly, unless I introduce rel="external' in the href link !!! I suppose it means it IS NOT AJAX anymore? Also I am unable to find the reason..
Further independent of the above topic, I face another issue. The loading time (i.e. Time taken to display the To-Page) varies.
Mostly it is OK, but at times the loading-circle goes on forever.... and I presume it has crashed....??? then If I go back using the back button and come forward again, many times it loads immediately...!!!!!
Any thoughts or suggestions.....?
Thanks in anticipation...
Ratna
Before you can worry about how to pass attributes from one page to another you need to understand the difference between multi-page and multi-HTML templates.
Multi HTML page template
Smaller and lighter, each data-role=”page” is inside a separate HTML file and page structure is much more modular.
Can become even smaller if every subsequent HTML page is stripped from HEAD content, or anything that isn’t data-role=”page” div. Unfortunately in this case fallback if JavaScript is not supported is out of question.
DOM size is relatively small, only first page is permanently loaded into the DOM, any other page will also be loaded into the DOM but at the same time it will also be removed when not used actively, basically each time you move from it.
Better fallback if JavaScript is not supported. Works great in desktop browsers after a page refresh, mainly because every HTML page has an existing HEAD content. This also allows your app to behave like normal web app mainly because AJAX can be turned off.
Multipage template
Since all pages are already loaded, no additional requests are generated for navigating between pages.
First load is slower as the file size is larger, but subsequent page navigation is fast, thus making transitions much more smooth. Almost native-like smooth, emphasize on almost.
Suitable for relatively smaller applications and situations where you know the capabilities of your target platforms including presence of JavaScript support, thus making it a great solution for a hybrid app. It works much better as a Phonegap app then multi HTML template.
The “page” data-role element is required.
More about this topic can be found here: Multipage template vs Multi HTML template in jQuery Mobile
Now let's talk about how to properly pass data between jQuery Mobile pages.
jQuery Mobile uses AJAX by default
You can turn off AJAX using rel="external"
If you turn off AJAX you will lose almost everything good about jQuery Mobile, including animations. So if you don't want AJAX page handling better find some other responsive framework like Bootstrap or Foundation.
If you don't want to use AJAX you can still use querystrings but inside a href or via changePage function.
Better querystrings alternatives:
Global object.
If you're using AJAX you can simply use a global object(s) to store all of your data.
Something like this:
// Store object
var storeObject = {
parameter1: null,
parameter2 : null
}
Access data from the previous page
Again if you're using AJAX you don't need to pass any data because all that data is till in the DOM.
// Store object
$(document).on('pagebeforeshow', '#second', function(e, data){
alert("My name is " + data.prevPage.find('#test-input').val());
});
Localstorage or Sessionstorage
This solution will work no matter if you use AJAX or not.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#change-page-button', function(){
// store some data
if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}
// Change page
$.mobile.changePage("#second");
});
});
$(document).on('pagebeforeshow', '#second', function(){
alert('My name is ' + localStorage.firstname + ' ' + localStorage.lastname);
// Lets change localStorage data before we go to the next page
localStorage.firstname="NewFirstNeme";
localStorage.lastname="NewLastName";
});
$(document).on('pagebeforeshow', '#third', function(){
alert('My name is ' + localStorage.firstname + ' ' + localStorage.lastname);
});
Send data through changePage function or via href
// Send
$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true});
or
Send parameter
receive that same data:
$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
If you need more information about this solutions including working examples find them here: Passing data between jQuery Mobile pages
Several methods mentioned here are deprecated (still usable) in the version 1.4. Though you don't need to worry about that, almost everything here will be unusable in version 1.5. This new version will overhaul jQuery Mobile from the bottom to the top.
Update
Yes, you can use any such link and jQuery Mobile will use AJAX. If you take a look at my previous examples you will find a working one.
If you want AJAX you CAN'T use rel="external", data-ajax="false" though stringquerys will work in bot cases.
Correct they will only work in multi-HTML template. Though there used to be a 3rd party plugin that allowed this to work with multi-page template but I don't think it works with newer jQuery Mobile versions.
Correct, if you want to link external page you need to use rel="external".

Upgrading to new asynchrous Google Analytics code - should you do it?

I had read somewhere and have now forgotten that upgrading to the new asynchronous code will not enable one to track actual clicks for downloading items when user stays on the same page and that for tracking that you need to use the old version of GA code.
My question is, is that still the case and does anyone have any other reasons for not upgrading to use the newer asynchronous tracking?
thanks
Hmm...are you sure the "old" version of GA automatically tracked downloads? AFAIK GA never automatically tracked download links, that you always had to attach GA code (like a _trackEvent call) to your links yourself. But in any case, it's pretty easy to do it yourself, so it's really not a big deal. Plus, you get lots of benefits upgrading, and one day it may not even be an option to stick with the old version...
If you have jQuery you can for example do this:
// file types you want to consider a download
var downloadFileTypes = ['pdf','doc','docx','mp4'];
$(document).ready(function() {
$('a').filter(function() {
var ext = $(this).attr('href').split('.').pop().toLowerCase();
return ( $.inArray(ext, downloadFileTypes )>-1 );
})
.click(function() {
_gaq.push(['_trackEvent', 'Downloads', $(this).attr('href')]);
});
});
If you do not have a framework like jQuery, you can still do this easy enough with .getElementsByTagName() and using regular loops and conditions instead of the jQuery conveniences like .filter and .inArray
edit: Some things to note about that example:
the jQuery code was an example to hook the GA code to standard links pointing to the file types you specify in downloadFiletypes. It will only apply to links that exist at the time the code is executed. If you have links that may be dynamically generated on the page later, consider looking into .on() instead of .click()
you will need to make tweaks to matching links you want to consider downloads if they do not point to regular files with extensions. For instance, some websites have a controller script that expects a parameter with an ID and it dynamically serves up a pdf or whatever..if your files are like this, you will have to alter the logic to look for that instead.

Trying to use the swfobject.js youtube object inside of WordPress

I need to use the extra powers of the swfobject api. This object is a new way of embedding Youtube videos into web sites.
Pasting code that I found from Google's tutorial directly into the WordPress editor was in-effective. WordPress would not treat this as active code.
So, I created a new template file and inserted my code into that file. This worked relatively well. The code went live and I got the extra feature that I was looking for, which was that I am able to have the visuals of the video autoplay, and to have the sound muted by default.
However, this has messed up the layout and flow of my menus which where just above the video.
Can anyone tell me where to proper place to put this code is, or is this question too specific. If it will help you can see the messed up page at:
http://bestoftimesusa.com/home-mute-test/
and how it is supposed to look at:
http://bestoftimesusa.com
The fully functional code that got embedded is this:
<script type="text/javascript" src="/wp-includes/js/swfobject/swfobject.js"></script>
<div id="ytapiplayer">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
var ytplayer = false;
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/v/IBjstQceGBk?enablejsapi=1&playerapiid=ytplayer&version=3&autoplay=1",
"ytapiplayer", "370", "238", "8", null, null, params, atts);
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
ytplayer.mute();
}
</script>
</div>
Unless you want the same youtube video to appear on all pages (of a certain type), I don't think putting that entire block in your template files makes sense. The only part that really makes sense for a template file is the first line. The lines after that are video-specific.
By default, WordPress filters out javascript from posts. You can disable that filtering with a plugin which would allow you to include javascript in your posts.
Using that plugin, you can set javascript filters on a global or per-post basis. It seems like a per-post basis would work for you so I'd go with that, just enabling it on the page I wanted.
Two last things:
You could put the first line in one of your template files to eliminate having to put that in every post
You have one opening <div> tag but two closing </div> tags, that could be expected, but I'd double check.

Going "Stateless" and loading scripts dynamically

What I want to know is if I am approaching this from the right angle.
I have an asp.net app I am building. I am using a Masterpage for the overall look of the app (below you can see the code).
I'd like to have the menu system use a dynamic load like jQuery's .load() function to load the content. That is fine and I have that down. The .load() function uses innerHTML to pump that content into the page. This is a problem if on that page you want to load module specific scripts and styles.
My question is, in an environment such as this, how do you guys load your scripts for these modules? Should I load every script on the initial load of the app? This app will not ever be "that big" however I want to make sure I do it right just in case.
MasterSheet
<div id="primaryNavigation">
<ul>
<li class="current">Main</li>
<li>Some Overview</li>
<li>Reporting</li>
<li>More Reporting</li>
<li>About</li>
</ul>
</div>
<div id="mainContentContainer">
<asp:ContentPlaceHolder ID="cphBody" runat="server" />
</div>
Example Module inside of the Content tag
<div id="container">
Inside a page
<script id="scriptToLoad" type="text/javascript">
alert('Something');
head.ready(function () { console.log('please print'); });
</script>
</div>
<div id="includeScripts">
../Files/Javascript/SomeModuleSpecificJs.js
../Files/Javascript/SomeModuleSpecificJs1.js
</div>
My idea was to set up a div in each module that would have the id of "includeScripts" and load those from a method within the mastersheet like this. This method works (needs some tweeking obviously) however if the user keeps clicking on modules eventually every file will be loaded. If thats the case I might as well load them all on the mastersheet.
JS to be ran when the MasterPage is loaded
$navigation = $("#primaryNavigation").delegate('ul li a', 'click', function () {
$('#primaryNavigation').find('li').removeClass('current');
$(this).parent().addClass('current');
$('#mainContentContainer').load($(this).attr('href') + ' #container');
// Obviously this would overwrite the content from the container, this is merely proof of concept
$('#mainContentContainer').load($(this).attr('href') + ' #includeScripts');
var jsArray = $('#includeScripts').text().trim().split("\n");
$.each(jsArray, function (index, value) {
$.getScript(value);
});
return false;
});
I don't know about .load(), but JQuery's .html(), .append(), and a few other related functions will automatically run any script tags that they find in the given HTML. If load() doesn't do that for you, it should be easy enough to use $.get(..., function(){$('#myElement').html();}); instead. You could even write your own extension specifically for this purpose.
Style sheets may be a different story. I've typically just used a single style sheet per page.
Edit
I just spent some more time reading your question, and I realized that I didn't answer it fully.
Should I load every script on the initial load of the app?
It really depends on the size of your scripts and the way you expect users to interact with your system. In this seminar, the people who made Google Wave talk about how they addressed this issue. At one point the speaker says, "Perceived latency is the most important thing to optimize for." The problem was, in an early version, their javascript file (optimized and compiled by GWT) was a few megabytes in size. People with a slow connection (a cell phone browser, e.g.) would have to wait a long time for all this code to download before they could see what was in their Inbox. Their solution was to create "split points" in their code so that it could be loaded in chunks. The code necessary for displaying the Inbox could be loaded first, whereas the Contacts panel could wait until the user clicks "Contacts."
But you can take this too far. The other speaker in this video says the time spent in loading falls largely under one of two categories:
Fetching data you don't need, and
Too many HTTP requests
Each HTTP round-trip involves a certain amount of overhead, so it can be worthwhile to load some code you don't need yet in order to avoid having to make another round-trip in a few milliseconds when you realize you need it.
Since you say:
This app will not ever be "that big"
... I'm guessing that you'll probably fall mostly under the latter category (too many HTTP requests). The best thing to do in that case is:
Use a tool like Chirpy to consolidate all your javascript files into a single file (which can be automatically minified when not in Debug mode).
If your application has a login page that doesn't use all this javascript functionality, add a script tag for this javascript file at the bottom of the login page so that the user's browser will download the file behind the scenes while the user is busy entering their username and password. The master page for the rest of the site should simply include the script file once in a standard script tag.
Make sure your site's caching rules are set up properly so that user's browser will only request this file once.
Make sure your site is set to compress this javascript file since javascript (especially minified javascript) lends itself to gzip compression very nicely.
Once you've done this, you should find that there is no "perceived latency" from loading your javascript file.
If your application does eventually become "that big," you'll want to break your program down into modules like the Google Wave team did. But choose your modules based on how you expect the system to be used. If only a small handful of users is likely to use your admin interface, for example, you'll want to put all of your admin UI code into a separate module that "normal" users will never have to download.
When deciding where to draw the line, UI experts basically say one-fifth of a second is the point where the typical human's brain starts wondering, "Did that work?" If a user clicks a button and has to wait longer than that before they see something happen, you've reached the point of "perceived latency." Anything beyond that will become increasingly annoying to the user.

Preferred method for linking to stylesheets from a UserControl?

We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript.
So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think.
Does anyone have any preferred methods, and if so, what and why?
I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think.
It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag & drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well.
This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not.
Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it.
When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself.
What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page_Load of the UserControl, but that just seems like ass.
I could use #import I guess but I think link tags are preferred, correct?
It sounds like you're rolling your own theme engine... why not use ASP.NET Themes?
If you're determined to do it yourself, here's some code from the CssFriendly project that may be of interest to you. (I think it should be ok to post the code as long as I cite where it's from.) The .css files are flagged as Embedded Resource and the code below is used to include them as needed.
string filePath = page.ClientScript.GetWebResourceUrl(type, css);
// if filePath is not empty, embedded CSS exists -- register it
if (!String.IsNullOrEmpty(filePath))
{
if (!Helpers.HeadContainsLinkHref(page, filePath))
{
HtmlLink link = new HtmlLink();
link.Href = page.ResolveUrl(filePath);
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
page.Header.Controls.Add(link);
}
}
I think what you're supposed to do is use Page.RegisterScriptBlock to register your script blocks. Best-case you shouldn't have them inline in your ascx inside script blocks. This isn't always possible, but theoretically it's the best way.
Ideally your styles should be separate from your markup as well. Your controls can have classes and IDs, but your style is based on your application and not your controls. Controls can theoretically be used in other applications where you might want a different style.
It depends on how big your app is, and whether or not it's dependent on Themes elsewhere, IMHO.
If you're using a .skin file, or if the majority of the app is also plugged into the theme, you might as well go with the theme.
But if it's just a few styles you need, you're better off to set the stylesheet manually, keep your css file external (inline styles are a PITA and defeat one of the core purposes of css).
In either case, don't forget to set the CssClass attribute on your controls.
To be proper I would have an import.css file - structure the naming of the classes to follow your controls, and import the styles within the header of the document.
If you have a module called "30DayPricingCalc" then you could name the classes/id's:
30DayPricingCalc.css
.30daypricingcalc_main_content
{
...
}
Also if you haven't I would setup a list of generic reusable styles to save you room. Since elements will allow multiple classes per object.
Also, link tags matter a lot less now than they used to. we're well past support for IE5 generation browsers and IE6 supports the #import tag.
Cheers!

Resources