I currently have a single jQuery script page that I include in my ScriptManager on my MasterPage (I use ASP.NET). All of my custom scripts for all my pages go in this page. I know some people like to break it up into multiple pages but I prefer having them all in one place. Anyways, I have one $(document).ready(function(){ //do stuff// }); on this page. All of my other functions I name and then place in the document.ready function, ie:
$(document).ready(function(){
Function1(); //necessary for page1.aspx, page2.aspx but not 3 or 4
Function2(); //etc., necessary for some but not other pages
});
function Function1() {
// whatever, etc //
}
My question centers around the efficiency of this. A lot of these functions only have any sort of application on certain pages, but not on all. Would it be better to include some page-specific coding, ie, determine what page we're on, and then if we're on the correct page, go ahead and perform the function, or does it not even matter? I was under the impression that it didn't matter, but I would like to be sure.
Thanks
You might consider putting everything into an external .js file. Then the browser only has to download the code once.
If the functions cause errors on pages where they're not not needed, you should only include them on pages where they are needed.
Otherwise, it depends on how long it takes the functions to execute. If it's not noticeably long, I would say don't worry about it. It's not worth the fragility you'd introduce by adding a bunch of if statements.
I can't say if this is a definitive answer, but where possibly in any project i try to display and show as little coding as possible that is not relevant to that page.
So in the case of JQuery, i would only display the javascript code required for that page by doing a server side check.
But i guess this would really depend on how large the code your using, if it's a small one line script in jquery then i don't think you're really going to lose out, but if you have a lot of logic in there, then i would recommend breaking it down per page that requires it.
Depending on the number of page-specific functions, it could matter a lot.
If you have a small amount of extra data then you won't see any noticeable performance decreases. However, as your code base grows it could become a mess to maintain that code.
Additionally, you are pushing extra bits across the wire in every page request, as traffic increases that may add up to extra costs on your bandwidth.
Yes. It matters. The real question is how complicated those functions are. If you think the code to check if the functions are needed would be more time consuming than running the code, then it's not necessary.
So that is the question you need to ask yourself (or test): Does it take longer to test if I need the function, or just to run them?
Related
A site I'm working on has two different pages, and each one is attempting to do the same thing. One of the pages, though still in use, has not been updated and so the code is no longer doing everything it is meant to do.
Rather than continue this wet solution and copy the missing code, I would like to make use of the code that has been updated. Ideally I would copy the function into a helper class or make a base class to provide this functionality, but the one function calls many private functions, and each of the private function mixes business logic with the presentation logic.
I have no documentation and a short time scale, so to do this would not be feasible. So my question is, what are the disadvantages of calling the function on page1.aspx from page2.aspx? It is a shared function so I'm hoping it will be OK but advice would be appreciated.
Sounds like a bloody mess to me. You are not to descript but without really seeing whats going on it is hard to say. If this code is touching dom elements and hitting page cycle events it will probably be a pain. I would say.. take the actual business logic and put it in another class outside of the page and then reference the business logic that way but for dom elements directly webforms is already over complicated I would try staying away from making it worse. Perhaps you can pull these dom elements into a user control and reuse it on both pages? Either way sounds like you have plenty of fun a head of you :)
It would be best if you showed some of the code, but I have to say that if the two methods are Shared, then you're probably ok.
However, such Shared code doesn't belong on either page. It belongs in some other class that can be accessed by both pages.
I am about to implement a function that loads potentially large set of data (~1000 rows with ~10 columns). I am planning to implement a infinite scolling solution (ajax, jQuery, asmx) as a performance measure. However, if a user has javascript disabled or the googlebot comes a-crawling, I would like to generate the entire set of data all as once, so that no data becomes inaccessible for either of those two scenarios.
I'm not sure what approach to use here. Should I look towards the noscript-tag perhaps?
In my experience if you're expecting a 1000 rows and expect any sort of traffic you would need to offer two scenarios.
I would use the noscript tag and then offer a paginated view for non js users. Or, you can do as I have done in the past and simply explain that your application requires that javascript be left on (also through the noscript tag). Anyone that runs around the internet with javascript turned off is most likely going to be used to the internet not working the way it should, or only getting a partial experience.
Try to use a client-side pagination class with JS,
its lightweight, very user friendly and if browser doesnt submit JS,
No problem, he will see a huge data table :)
http://en.newinstance.it/2006/09/27/client-side-html-table-pagination-with-javascript/
I just worked out, by trial-and-error, that IE 7 has an upper limit of 32 stylesheet includes (i.e. tags).
I'm working on the front-end of a very large website, in which we wish to break our CSS into as many separate files as we wish, since this makes developing and debugging much easier.
Performance isn't a concern, as we do compress all these files into a single package prior to deployment.
The problem is on the development side. How can we work with more than 32 stylesheets if IE 7 has an upper limit of 32?
Is there any means of hacking around this?
I'm trying to come up with solutions, but it seems that even if I loaded the stylesheets via Ajax, I'd still be writing out tags, which would still count towards the 32-stylesheet limit.
Is this the case? Am I stuck with the 32-file limit or is there a way around it?
NOTE: I'm asking for a client-side solution to this. Obviousy a server-side solution isn't necessary as we already have a compression system in place. I just don't want to have to do a re-compress every time I make one little CSS change that I want to test.
Don't support IE7.
To avoid confusion: I'm not seriously suggesting this as a real solution.
Create CSS files on the server side and merge all files that are needed for this certain page.
If you are using Apache or Lighttp consider using mod_concat
Write your stylesheet into an existing style block with JavaScript using the cssText property, like this:
document.styleSheets[0].cssText += ourCss;
More info here:
https://bushrobot.blogspot.com/2012/06/getting-around-31-stylesheet-limit-in.html
At my last company we solved this by mashing all the CSS into one big document and inserting a URL in the web page that referenced that one-shot document. This was all done on-the-fly, just before returning the page to the client (we had a bunch of stuff going on behind the scenes that generated dynamic CSS).
You might be able to get your web server to do something similar, depending on your setup, otherwise it sounds like you're stuck with only 32 files.
Or you could just not support IE7 ;)
I have quite a number of user controls that I need to embed in Umbraco macros. Each user control has quite a bit of in page javascript that needs loaded into the page.
I have been building up the javascript with StringBuilder.Appendline then registering a startup script with code behind but this stinks and I feel there has to be a better way of going about this.
Has anyone any ideas please?
Thanks,
B
If the javascript isn't dynamic, that is that it changes based on the usercontrol you would probably be best to extract it and put it in either one .js file for the site or in a number of them. Doing so allows it to be cached by the browser.
If it is dynamic then I would personally keep it isolated inside the control rather than try to write it out all at once. I don't believe there is any major performance hit from having several script blocks, although I could be wrong.
Now a community wiki!
I want to make it clear first: This isn't a question in relation to server-side Javascript or running Javascript server side. This is a question regarding rendering of Javascript code (which will be executed on the client-side) from server-side code.
Having said that, take a look at below ASP.net code for example:
hlRemoveCategory.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this?');")
This is prescribing the client-side onclick event on the server-side.
As oppose to writing Javascript on the client-side:
$('a[rel=remove]').bind('click', function(event) {
return confirm('Are you sure you want to delete this?');
}
Now the question I want to ask is: What is the benefit of rendering javascript from the server-side code? Or the vice-versa?
I personally prefer the second way of hooking up client-side UI/behaviour to HTML elements for the following reasons:
Server-side does what ever it needs to already, including data-validation, event delegation and etc; and
What server-side sees as an event is not necessarily the same process on the client-side. i.e., there are plenty more events on client-side (just look at custom events); and
What happens on client-side and on server-side, during an event, could be completely irrelevant and decoupled; and
What ever happens on client-side happens on client-side, there is no need for the server to know. Server should process and run what is given to them, how the process comes to life is not really up to them to decide in the event of the client-side events; and so on and so forth.
These are my thoughts obviously. I want to know what others think and if there has been any discussions on this topic.
Topics branching from this argument can reach:
Code management: is it easier to render everything from server-side?
Separation of concern: is it easier if client-side logic is separated to server-side logic?
Efficiency: which is more efficient both in terms of coding and running?
At the end of the day, I am trying to move my team to go towards the second approach. There are lot of old guys in this team who are afraid of this change. I just wish to convince them with the right facts and stats.
Let me know your thoughts.
UPDATE1: It looks like all of us who have participated in this post have common thought; Good to know that there are others who think alike. Now to go convince the guys ;) Thanks everyone.
Your second example is vastly superior to the first example. Javascript is your behaviour layer and should be separate from your semantic markup (content) and CSS (presentation). There are a number of reasons this is better architecture:
Encourages progressive enhancement. As you mentioned, the backend code should work correctly in the absence of JS. You cannot rely on your clients having JS available. This way you build it once without JS and then can enhance the experience for those with JS (e.g. by adding clientside validation as well as serverside validation so that the client can get instant feedback)
Cleaner markup. Normally reduced download size. One reusable selector in a separate JS file that can be cached and shared between pages vs. a handler on each element.
All of your JS in one re-used place. e.g. if your code was opening a popup window and you decided to change the dimensions of the window you would change it once in the code in the JS file vs. having to change it on every individual inline handler.
There are lots of other arguments and reasons but they should get you started...
Also, from your example it appears that you have a normal link in your document which can delete content. This would also be a bad practice. Anything that deletes or updates content should be done on a POST (not GET) request. So it should be the result of submitting a form. Otherwise e.g. googlebot could accidentally delete all of your content by just crawling your page (and search engine robots don't execute JS so your alert wouldn't help there)
The two biggest differences i can think of up front are:
you lose the client side caching you would get if the javascript was in a separate js file
if you need to change your javascript, you have to recompile (extrapolate this to what happens after you have released your product: if you have to recompile then you need to redistribute binaries instead of just a modified js file)
it is easier to use the VS debugger if the javascript is in a separate file; you can just set a break point in that file, if you are generating the code server side then you have to use the running documents feature, find your generated code and then add the breakpoint, and that breakpoint has to be manually added everytime you re-run your app. Following on from that, if the code is in a separate file, then you can just make your tweak to the javascript code, F5 your browser page, and keep on debugging without having to stop and restart the debugger.
It should be mentioned that sometimes you have to insert js code from the server - for example if the bulk of your code is in a separate js file and you need to insert control identities in to the page for that code to work with. Just try to avoid that situation if possible.
Looks like you already know what to do. Rendering it on the server side is a bad idea.
The simple reasoning being you're Javascript lives both on the server side pages as well as in separate Javascript files (assuming you are using Javascript at all). It can become a debugging nightmare to fix things when everything is everywhere.
Were you not using any other Javascript besides what the server side scripts generate, it would probably be fine and manageable (forget what the unobtrusive movement says).
Secondly, if you have 100 links on the page, you will be repeating that same code in 100 places. Repetition is another maintenance and debugging nightmare. You can handle all links on all pages with one event handler and one attribute. That doesn't even need a second thought.
<Rant>
It's not easy to separate HTML and Javascript, and even CSS especially if you want some AJAX or UI goodness. To have total separation we would have to move to a desktop application model where all the front-end code is generated on the client side programmatically using Javascript, and all interaction with the server gets limited to pure data exchange.
Most upstream communication (client to server) is already just data exchange, but not the downstream communications. Many server-side scripts generate HTML, merge it with data and spit it back. That is fine as long as the server stays in command of generating the HTML views. But when fancy Javascript comes onboard and starts appending rows to tables, and div's for comments by replicating the existing HTML structure exactly, then we have created two points at which the markup gets generated.
$(".comments").append($("<div>", {
"id": "123",
"class": "comment",
"html": "I would argue this is still bad practice..."
}));
Maybe this is not as big a nightmare (depending on the scale), but it can be a serious problem too. Now if we change the structure of the comments, the change needs to be done at two places - the server side script and templates where content is initially generated, and the Javascript side which dynamically adds comments after page load.
A second example is about applications that use drag and drag. If you can drag div's around the page, they would need to be taken off the regular page flow, and positioned absolutely or relatively with precise coordinates. Now since we cannot create classes beforehand for all possible coordinates (and that would be stupid to attempt), we basically inject styles directly in the element. Our HTML then looks like:
<div style="position: absolute; top: 100px; left: 250px;">..</div>
We have screwed up our beautiful semantic pages, but it had to be done.
</Rant>
Semantic, and behavioral separation aside, I would say is basically boils down to repetition. Are you repeating the code unnecessarily. Are multiple layers handling the same logic. Is it possible to shove all of it into a single layer, or cut down on all repetition.
You and the other people answering the question have already listed reasons why it is better not to having the server side code spit intrinsic event attributes into documents.
The flip side of the coin is that doing so is quick and simple (at least in the short term).
IMO, this doesn't come close to outweighing the cons of the approach, but it is a reason.
For the code in your example it doesn't really matter. The code isn't using any information that is only available at the server side, so it's just as easy to bind the event in client side code.
Sometimes you want to use some information that is available at the server side to decide whether the event should be added or not, or to create the code for the event, for example:
if (categoryCanBeDeleted) {
hlRemoveCategory.Attributes.Add(
"onclick",
"return confirm('Are you sure you want to delete the " + categoryType + "?');"
);
}
If you would do this at the client side, you have to put this information into the page somehow so that the client side code also has access to it.