How to access serverside context from `.js` file? - asp.net

I have to move all my scripts into a separate .js file. But I have wired the code in the client (*.aspx) file, with code such as
<script>
var x=<%=ViewData["Key"];%>
</script>
I'm sure there will be an issue when I move that line to the js file as the server side context can't be accessed.
How do I solve this issue?

The most straightforward thing to do is to move all JS code except these variable assignments.

Effectively, the trick is dependency injection in javascript. First, abstract the variables you are generating from server-side variables into parameters for your javascript methods and objects. Then use a small amount of script in-page to setup the javascripts to run.
If you are dealing with a few rather static things (eg--some path names), another tactic is to create a javascript "configuration" object that is in a separate, server-generated script, that can be called by your other scripts as needed.

Related

In Magnolia CMS, how can each component declare its required javascript files?

I am using Magnolia CMS 5.3.4, the STK, and freemarker (FTL) template scripts.
Some components I have defined relies on specific javascript files. Right now, what I do is that I include these javascript files in the main.ftl template script. I am looking for a way to get them included only if the specific component is present on the page.
I tried to use the jsFiles property in Template Definitions, but it seems it works only for page template definition.
The jsFiles property indeed works only for pages not for components. This is because Magnolia wants to include those files in header already, rather than loading them in middle of the body when component gets rendered.
As a general practice I would anyway recommend combining your js files into one (look at for example plugin loader in resources on how this is done) and set longer time for caching such file so that browser downloads all the script just once for the whole site rather then page by page. The bigger js file you are sending over the more overhead you are cutting off from requesting separate files and better the compression of content for transport will work.
HTH,
Jan

Meteor : Load javascript file but don't execute. Execute on demand

I want to load a javascript file but do not want a "<script type="text/javascript" src="..."></script>" tag created for it.
I am using iron-router. So, I want this js file to execute in 'onAfterAction' hook, i.e. after the template is loaded.
I am thinking of following ways to do this:
One way is place this file in "public" directory and use '$.getScript' function to load and execute this on demand. But, these files won't get minified and compacted to one file. Also, this will need another fetch on the n/w.
The other way is to create a package and include this file in the package. But, then I will have to enclose the whole file in a function and 'export' this function in package. And execute this function on demand.
The third way is to put these files in 'client' directory and call "$.getScript('/client/js/...". But, the js file would get executed twice as a "<script type="text/javascript" src="..."></script>" tag will be created for it..
Is there a better way of doing this so that the file is locally available and can be executed on demand?
From what I understand about Meteor. All JavaScript executes without having to load a <script></script> tags. Depending on how you seem okay with it being a public script, I'd put it in the client folder and utilize the Template.[your-template-name].rendered in some way where you can load that particular script after the template is rendered.
http://docs.meteor.com/#/basic/Template-onRendered

Load-time initialization for hidden controls

Our web application started out as a big, honkin' ASP.NET AJAX 'page' with oodles of controls on it. They all shared a small set of large .js and .css files. I need to use some of these controls in other, unrelated pages around our site. The difficulty is in all the other stuff the .css and .js files bring along with them when I try to use those controls elsewhere - too much and there's a lot of bloat, too little and the controls don't work.
So, I've been experimenting with breaking up the .css and .js and writing the controls to register the .js and .css they need. Initially I will end up with many more but smaller .js and .css files, but I can combine them at run-time later. I just want to encapsulate these controls so the pages that use them know less about what it takes to use them.
But I am running into a problem. I am using OnInit or OnLoad to register the .css and .js as needed. Unfortunately, none of these methods is called if the control is not visible the first time you hit the page when all the .css and .js needs to make its way to the client. It isn't until later on that the controls are enabled for thier specific functions that they are visible and could emit the .js or .css. Then it's too late!
Do I have to bite the bullet and hand-include the right .css/.js on the pages I use these controls on, or is there a better way to 'inventory' the controls in use to get them to emit what they need?
I assume that the problem you are facing is that some controls are loaded dynamically (i.e. in an update panel). It is a tricky problem - usually because you don't know in advance what controls you will need and thus what JS + CSS to include.
Perhaps you should consider loading the JS and CSS dynamically using a script loader?
The YUI script loader and the new MS one spring to mind (but I am sure that there are dozens of other equally good ones out there).
See this previous answer for a couple of potentially useful links. Also see here for more about the MS script loader and YUI scriptloader.
Being that you are already using MS stuff I would recommend the MS script loader but as far as I know, the MS script loader does not support managing your dynamically loaded CSS (if anyone knows different please correct me) and so maybe the YUI solution might be more suitable (or maybe you can roll your own way of dynamically adding CSS if it has not already been added - it shouldn't be too hard).
Using a script loader removes the headache of working out up front what you need to include but it may require some changes to your javascript. In particular, if you have any javascript inline in your control's markup that relies on functions declared in the javascript you are dynamically adding.
E.g. If you current have user control markup like this
<div id="my control">
<script type="text/javascript>
foo(); // foo is defined in foo.js, which is included in a script element in the head
... more script ...
</script>
....
</div>
Then using a script loader you must change it to look like this
<div id="my control">
<script type="text/javascript>
var onLoadHandler = function() {
foo();
... more script ...
};
Sys.loader.registerScript("foo_package_name", null, onLoadHandler);
</script>
</div>
You may be able to include the js and css files in with the rendering for the controls that you are using. Basically adding them into the first line of the html that is generated by the control. I know you should be able to put in the include for the js files anywhere in the html, although I've yet to try it out with the css files.
If that works, you may want to put in some logic to make sure that the files are only included once if you have more than one of those controls. This shouldn't be too hard to do at the javascript level.
I'd be interested to see what you get working, because I've been looking at doing something similiar where I'm currently working.

In an ASP.NET MVC site, where would the JQuery code go?

I'm just getting started with ASP.NET MVC. I'm going to be using JQuery on the website I'm making, but I'm not really sure about one thing: where would JQuery code be placed?
This concerns two things:
Where do I import the JQuery JavaScript file? (I've been thinking that the Master page would be a good place to do this; am I right, or do I have to import it in each view?)
Should all my JQuery code be referenced from the Master page (i.e., I store my code that uses JQuery in a separate .js file and reference it in a <script> tag)?
Thanks in advance.
Anything that you will use in every page put a import in your master. If its something that you will only use on a smaller scale, put the import in the view that will use it.
The key is to not load unnecessary bytes when they won't even be used. I have a universal js file that contains anything that will be used as more common functions across the board imported in my master. Then on a page by page basis, I have only the js imports that I need for that page.
If you put every js import in your master that means it will load that js on every page, when maybe half of them aren't even used for that particular page. That can have a big impact on page load times.
I suggest also using something that can compress the js to a minified version for production. Telerik has their Script Registrar and it's a really nice tool as well.
Add JQuery to the bottom of Site.Master just about the body tag. This means the page will load and not wait for the Javascript.
But the JQuery relevant to each view, but add on a View level.
You should import your JQuery library on the master page. Probably you'll use JQuery on most of the views so having the reference in only one place it's most welcome.
Normally it's a good practice to have all javascript code you can in separated files, as less inline javascript as you have the better. 2 reasons: more readable code and better performance since external javascript files are cached.
My jquery code is placed in the head of the masterpage since it's used on just about every view on the site. The only reason you wouldn't do this is if you're only using the jquery library on a few of your views, in which case there's no reason to load it up for every user.
You should let Google host jQuery for you.

Where should I put my JavaScript - page or external file?

In VS 2008, I have an ASP.NET content page having one master page. I would like to add JavaScript functions for client side validation etc. for this page. My questions are:
Should I write these scripts in a separate .js file, or embedded within the .aspx file.
Does this choice affect the performance of the website?
Are there any rules for writing a JavaScript file?
I would say, you should create javascripts functions into separate .js file and link them up inside the the master page or .ASPX where it's needed.
Imagine you "copy and paste" the javascripts functions in each of the .ASPX, then when that .ASPX file is loaded, it will take longer to render that page since it needs to render also the javascript functions. If you maintain it into separate .js file, the browser will only download once if it's newer or not exist before.
You can also cache those .js files, so that the browsers won't reload it everytime.
The other advantage is when you need to make some changes in the .js files, you just need it to modify it centrally at one file, rather than do a "Find and Replace" through numerous .ASPX
You should consider the power of caching, if the JavaScript functions are likely to be used on several pages a user will visit. In this case you should put them in (if possible) one external .js file. With this the file will only get fetched once from the server and then stays in the browser cache. Your HTML pages get smaller (significantly for larger JS libs).
If the functions (typically validation rules) only apply to one single page only, an external JavaScript file would lead to an extra HTTP request that leads to a short blocking in the user's experience of your page. Here it's better to embed the JS in the HTML file.
See Yahoo!'s tips on this for more detailed hints.
Cheers,
It depends on your use. If its a page specific functionality then try and implement it in the page itself. If it is used by many pages then put that inside a js file.
Does it affect the performance of
website?
Yes, it can. If you have a js file with thousands of lines of code and in a page you have to call only one function inside the js file. If you refer the file for this one there should be a bandwidth wastage in downloading the entire file. For this case you can write the function inside the same page itself.
On the other side browser can cache a js file. So for subsequent requests if the file is present in the cache it won't be downloaded again. But in the case of JavaScript being written in the page itself, every time the page loads all of its contents will be downloaded.

Resources