Javascript/Markup in Assembly - javascript

I'm trying to somehow render out javascript for a particular user control rather than just having a script include for the javascript file.
The reason why I don't want a simple script include is because I need to append unique ClientID's to the dom elements at runtime.
I could hardcode the javascript in a function and just append the ClientIDs. However, this will look messy and I'm not liking the idea of hardcoding javascript code in a class- it would be a nightmare to maintain.
What are some strategies that I can use to keep javascript/markup separate from the compiled code? I want to somehow have the javascript source included in the assembly as well so that as a user control, it would not require manual script includes and have no other dependencies for it to work.

I used this code from Rick Strahl's blog. Works awesome with jQuery and those types of libraries. http://www.west-wind.com/WebLog/posts/252178.aspx
HTH,
ck
PS If you're using a Web Application Project you can use javascript files as embedded resources.

Related

Include html files in an html file on a local file system?

I have a help system that is completely offline, no server, using file://.
I have one main page, with hundreds of line of html that represent many sections of the help system. I would like to stick each section in a html file and just include it. Unfortunately it seems like this is only possible with some nifty server side include techniques, with HTML5 (which I do not want to assume my users have), or with a nasty javascript hack where you copy your html file into js files with document.write calls for every line as written about here: Ways to include html in html.
What about something like handlebars.js or mustache.js? Can I use templating?
Since you don't want to use server-side includes, I would suggest using a static site generator (SSG).
If you are not familiar with SSG's, they allow you generate HTML pages from templates & includes (often Handlebars templates) and HTML, Markdown, JSON, or YAML, content using a CLI.
If you want to get started with an SSG, there are plenty of options, from Ruby based Jekyll, or Node.js based Assemble. In my opinion, Assemble is the best option and I would highly recommend it.

Using a Helper in a Vendor - CakePHP

In my CakePHP app, I am defining a Wizard vendor that outputs the HTML for a multistep Wizard type plugin, along with its relevant Javascript code. I'm wanting to use the JsHelper so that I can buffer my code to the bottom of the page.
Everything else is working, including my Javascript code if I just output it directly with the HTML. I just can't quite figure out how to use the JsHelper. Do I use a App:Uses or App:Import statement? When using it in a View, I can just define it on the controller level, but that doesn't work here.
$this->Js->buffer("
$('.mws-wizard').wizard({
buttonContainerClass: 'mws-button-row',
orientation: '$orientation',
forwardOnly: $forwardOnly
});
");
If you are developing this 'vendor' package yourself, you should not develop it as a 'vendor', but as a plugin.
The vendor folders are meant for including third-party libraries that are not developed with CakePHP in mind (for example to use parts of the Zend Framework in your application).
From the manual:
Note: Loading vendors usually means you are loading packages that do not follow conventions. For most vendor packages using App::import() is recommended.
Create a plugin not a vendor
To develop re-usable code that can be used with different projects/applications, develop your code as a Plugin. Plugins are basically 'mini CakePHP applications'. Classes from a plugin can be used inside your application and vice-versa; a plugin can use CakePHP helpers the same way as you use them in your application.
See Creating Your Own Plugins
Regarding the JsHelper
Contrary to the comment placed by Sam Delaney, your usage of the JsHelper looks fine to me. Adding some script to the Js buffer to output it in the layout seems useful. Just don't try to use it for extended blocks of JavaScript; that should be put in external .js files.
I do recommend to write the JavaScript code yourself and not have the JsHelper generate the code for you (e.g. Don't use $this->Js->get('#foo')->event('click', $eventCode);). This may be personal, but IMO this makes it harder to track/debug your JavaScript and isn't any more readable than just $('#foo').click('event code');
I've personally never found any use for the JavaScript helper in CakePHP as if you're not careful, you end with getting <script> tags littering your markup, which sometimes makes it quite difficult to debug. From what you describe, you have the JavaScript aggregated and appended at the bottom of your HTML so it isn't as bad as the situation I highlight previously.
Is it not possible to relocate all your JavaScript to .js files to encapsulate all the function for your wizard plugin/vendor? If you could do this, it would be in keeping with MVC principles where you could logically separate the view markup and presentation logic.

Automated method to add javascripts/css into local html files and execute them

I have a set of html files needed to be modified locally. So I found an easy way to do that: write javascript/css, attach them into existing html, run them in a web browser, and save the results back to html files. The problem is I have a very large set of html files to be processed. So I need an automation.
I would love to know how this task should be addressed. I found that there is an automated testing tool like Watir, but still wonder if this is the right option for the problem.
Specifically I use jQuery to easily parse and modify html pages dynamically. This is the reason I don't want to do it otherwise with, for example, Java which lacks support of good libraries for html parsing.
A "headless browser", like Phantom JS may help you.

References Asp.net JS files

I have a notepad filled with references to over 1k .js files. I would like for my page to check this file and add each as a reference eg:
<script type="text/javascript" src="####.js"></script>
any idea or examples on this.
Thanks
Not a direct answer to your question, maybe, but if you reference that many files maybe you should look at the Google closure compiler, or the Dojo build system, or search for javascript minifiers?
In addition to your page loading faster, you won't have to generate all those links.
Also not a direct answer, however you could simply create a control which is entered into your asp.net masterpage in the header and geneates your script tags.
However by itself that's going to cause serious performance problems with your website having references to so many javascript files.
I would serioulsy recommend that you look into using the AjaxToolkit (or other frameworks) to merge and minify all of your separate JS files into 1 file that gets generated dynamically.
The example I have below is for both CSS and JS which does minification and compression on the fly.
https://softwareengineering.stackexchange.com/questions/98810/how-to-organise-website-css/98818#98818

Where do you put your javascript?

Do you localize your javascript to the page, or have a master "application.js" or similar?
If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages?
EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.
And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do.
All shared JS code lives in the SITE/javascripts directory, but it's loaded in 'tiers'
For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.
There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)
For less-shared stuff (say my library that's only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.
For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the script tag will go below the button.
For inline JS that doesn't have a target (eg: onload events) it goes at the bottom of the page.
So, how does something get into a localised library, or a site-wide library?.
The first time you need it, write it inline
The next time you need it, pull the inline code up to a localised library
If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
If it's needed from more than one region, pull it up to a site-wide library.
A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view.
However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations.
I'd recommend using features like this rather than compromising the quality/readability of the actual source code.
Yahoo!'s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he's now at Google) and he's written some interesting tools that can help you decide where to put JavaScript.
I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I'll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).
In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I've found this style works well for me, especially when doing templating on a site. I build the template engine to "autoload" my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.
Personally, I try to include several Javascript files, sorted by module (like YUI does). But once in a while, when I'm writing essentially a one-liner, I'll put it on the page.
Best practice is probably to put it on Google's servers.
(Depends what you mean by "your" javascript though I suppose :)
This is something I've been wrestling with, too. I've ended up by using my back-end PHP script to intelligently build a list of required JS files based on the content requested by the user.
By organizing my JS files into a repository that contains multiple files organized by purpose (be they general use, focused for a single page, single section, etc) I can use the chain of events that builds the page on the back-end to selectively choose which JS files get included based on need (see example below).
This is after implementing my web app without giving this aspect of the code enough thought. Now, I should also add that the javascript I use enhances but does not form the foundation of my site. If you're using something like SproutCore or Ext I imagine the solution would be somewhat different.
Here's an example for a PHP-driven website:
If your site is divided into sections and one of those sections is calendar. The user navigates to "index.phhp?module=calendar&action=view". If the PHP code is class-based the routing algorithm instantiates the CalendarModule class which is based on 'Module' and has a virtual method 'getJavascript'. This will return those javascript classes that are required to perform the action 'view' on the 'calendar' module. It can also take into account any other special requirements and return js files for those as well. The rendering code can verify that there are no duplicates of js files when the javascript include list is built for the final page. So the getJavascript method returns an array like this
return array('prototype.js','mycalendar.js');
Note that this, or some form of this, is not a new idea. But it took me some time to think it important enough to go to the trouble.
If it's only a few hundred bytes or less, and doesn't need to be used anywhere else, I would probably inline it. The network overhead for another http request will likely outweigh any performance gains that you get by pulling it out of the page.
If it needs to be used in a few places, I would put the function(s) into a common external file, and call it from an inline script as needed.
If you are targeting an iphone, try to keep anything that you want cached under 25k.
No hard and fast rules really, every approach has pros and cons, would strongly recommend you check out the articles that can be found on yahoo's developer section, so you can make informed decisions on a case by case basis.

Categories