How do I make this popup code cleaner? - javascript

This is how I'm currently creating a popup for a few links on my site.
function popitup(url) {
newwindow=window.open(url,'name','height=615,width=475');
if (window.focus) {newwindow.focus()}
}
Is there a cleaner way to write this? Also, how do I make the scrollbar appear?

Be sure to change newwindow= to var newwindow=; otherwise you are declaring a global variable every time you run this function.
Otherwise, I agree with fsong's answer that it's a pretty basic function and doesn't need much cleaning. Here's what I would do, but it's minor stuff:
function popItUp(url) {
var newWindow = window.open(url, 'name', 'height=615,width=475,scrollbars=yes');
if (newWindow.focus) {
newWindow.focus();
}
}

I'm not exactly sure what you mean by a cleaner way, the code seems fairly straight forward to me. But you could get rid of the return in the onclick of the anchor tag since it's useless there and perhaps you could use underscore/camel case to name your function (pop_it_up or popItUp) for better readability.
For scrollbars add ,scrollbars=yes to the last parameter (strWindowFeatures) in window.open.

JSLint
I would check your code through JSLint.
JSLint is a JavaScript program that looks for problems in JavaScript
programs. It is a code quality tool.
Like author says JSLint will hurt your feelings, but I think the error you should certainly fix is:
Problem at line 2 character 3: 'newwindow' was used before it was defined.
This is issue exactly like Domenic said.
When you check your code with JSLint your code will also have better success when using tools like Javascript Minifier.
Make Javascript external
I also think you should make Javascript and CSS external.
Using external files in the real world generally produces faster pages
because the JavaScript and CSS files are cached by the browser.
JavaScript and CSS that are inlined in HTML documents get downloaded
every time the HTML document is requested. This reduces the number of
HTTP requests that are needed, but increases the size of the HTML
document. On the other hand, if the JavaScript and CSS are in external
files cached by the browser, the size of the HTML document is reduced
without increasing the number of HTTP requests.
I think you should read Yahoo!'s best practices, because it has a lot of very good tips to optimize your website(javascript).
Why popups?
But Why should you use popups? Some users block these, which renders your site unusable. I would advice you to use JQuery and just load content into the DOM.

Related

How/when/where to include external javascript

I'm looking for some advice on the best way to hold my JavaScript (jQuery) functions.
I am developing in MVC/razor and therefore have a layout page. I include my jQuery library and an external JavaScript file in here so it's available in every single page.
This is working well, but I am now becoming very aware of the fact that I am adding almost 300 lines of JS to EVERY page, where maybe half of that is used in any one of these pages.
One function is not in the external file and instead sits inside the HTML because I need to use variables set in my razor code.
I have a couple of questions around this arrangement:
Is placing JS inside the HTML generally acceptable when variables set using razor are used? There does not appear to be a clean way of passing a variable into an external js file
Should I split my functions down in to individual JS files and just include what is needed for each page in the site?
If I were to split them into multiple files, how would that work with jQuery's (document).ready ? Do I need to use that if all the JavaScript I am including is to be used?
I'm sure this will more a matter of opinion than a black and white answer, but I want to consider all my options before moving on. Even though it works fine as is, I can't help but feel there is a better/cleaner way.
Remember once a user lands on your homepage and loads the javascript file it will be cached in their browser so subsequent pages will not download the Javascript again.
I would definitely keep the js separate, you could have a snippet on each page that initialise the JS that that particurlar view needs. Put something like the below in the views that need to run JS
$(document).ready(function() {
mysite.mypage();
});
Then the function mysite.mypage() can be defined in the external JS file.
300 lines isnt the end of the world, I would say its probably too early to be worryign about optimisation.
You could always look at minifying that JS file to decrease the size. A quick and easy way to do this is here:
http://www.minifyjavascript.com/
Have you ever heard of require.js? http://requirejs.org/ I find it really useful.
It's a module loader so you are able to split all of your JS code into individual files and load only the ones you need on each page.
I don't know about passing a variable to an external JS file, I don't think its possible / the 'right' way.
You can make each external JS file into a function that accepts and returns parameters. Then in the page you need to use it:
- include the file dependancy
- call the function
Thats what I do, seems like your 2nd suggestion.
for the $(document.ready) question its really up to you. You don't have to use it but its useful for some things , check out this overview:
http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

How do you re-use javascript functions

We have lots of javascript functions, which are usually handled via the onclick function. Currently they are present in every file where-ever it is needed. Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed? What is the general practice here
<s:link view="/User.xhtml"
onclick="if (confirm('#{messages['label.user.warning']}')) {
var f = $('user');
f.method = 'POST';
f.action = f.submit();
} return false;">
Yes! Absolutely factor this out into an external javascript. Imagine if you needed to change something in this code. How many places do you have to change now? Don't duplicate code. It must makes your page bigger, which obviously affects how much is getting downloaded.
It's up to you to determine where the reusability lies in your own code. But it's easy enough (and a good idea) to create a library of often-used functions. Create a file like mylib.js, for instance, with things like...
function saveUser(f)
{
//...
f.method = 'POST';
f.action = f.submit();
}
add this to your pages:
<script type="text/javascript" src="mylib.js"></script>
add code your events like this:
<s:link view="/User.xhtml" onclick="return saveUser($('user'));">
Notice that the library code avoids any dependencies on the layout or naming of elements on the pages that use it. You may also want to leave little comments that will remind your future self what the purpose and assumptions of these library functions are.
Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed?
Ummm...yeah
It would be better to do something like this:
function saveUser() {
// logic goes here
}
and use the markup
<s:link view="..." onclick="saveUser();">
Using code inline like that is very bad. Don't do it. Or the prorgamming gods will grow restless.
It is always a good idea to put JavaScript code in JavaScript files. Like you don't mix content and presentation (XHTML and CSS), you don't have to mix content and interactivity (XHTML and JavaScript).
Putting JavaScript code in a separate file has several advantages:
No need to duplicate code (so better reuse),
Possibility to minify the source code, thing which is quite impossible to do if you put together XHTML and JavaScript,
Ability to use non-intrusive JavaScript, helping to create more accessible websites (there is probably nothing wrong from the accessibility point to use onclick and other events, but it becomes very easy to forget that the website must work without JavaScript, thus developing a non-accessible website).
Better client-side performance: larger pages make things slower; when you put JavaScript outside, the pages are smaller, and the .js file is cached by the browser instead of being loaded on every request.
Javascript can be accessed via a script tag, which can point to an external script or define it for use in this document only.
<script type="text/javascript" src="mycustom.js"></script>
<!-- OR -->
<script type="text/javascript">
function saveUser(username) {
//code
}
</script>
No offense, but if you didn't know that you are either very new at this or you skipped a lot of steps in learning javascript. I recommend going through the w3schools.com tutorial on javascript and anything else you'll be using.

Is it right to write multiple and separate <script > on a page?

While writing JavaScript code, I Separate each code block with <script> tags
<script type="text/javascript">
//---- code block 1---------
</script>
<script type="text/javascript">
----code block 2-----
</script>
<script type="text/javascript">
$(document).ready.(function(){
// code block3
});
</script>
I want to know that is it good practice to write separate <script type="text/javascript"></script> on the same page
--or--
We have to write all JavaScript code under one <script>
What are the technical differences in each way?
Well, you may want to ask yourself why your code organization scheme leads to that setup, and whether it causes maintenance or understandability problems, but I don't think it's strictly "bad". Now if your <script> tags are actually fetching separate files from the server, then it's a good idea to cut back on them.
The browser parses and interprets script tags in such a way that other work stops, so blocks of Javascript up at the top of your page can slow things down if they do a lot of work. That's true whether you've got a big block of code or several smaller blocks, however.
An advantage of moving to separate script files is that you can re-use code on multiple pages. When you do that, it may be easier at build time to compress your scripts with YUICompressor or some other similar tool.
The best reason to do this is if each script represents a discrete chunk of functionality which may not be used on (and therefore not vended to) every page. In that case, it becomes a smart strategy.
Having multiple <script> tags makes no real difference in performance but is less readable.
There is one edge case where multiple script blocks can make a difference (and I just learned about it). If one line of code references a value before it has been declared, this will work if the code belongs to the same script block, but not if they are separate. But this doesn't change the answer everybody gave you: it probably won't matter in everyday coding.
You don't have to, but its obviously cleaner that way, unless you want to clearly seperate the blocks of code.
Put all your javascript coding in separate and then call the file name. Because it is good thing. Coding execution is step by step, so it will take time if js present in between the coding.
Not nice, but not a problem.
Hunter is right, it makes absolutely no difference as far as performance is concerned.
When your javascript however becomes more complex, you may want to start building your own API of sorts and splitting out all of those tags into separate files. Then when you're deploying your app, find some sort of packaging solution that will combine all of those files to a single one, compress it using YUI compressor or Google Closure and have one single tag that references this file of all your code.
While it is a 'slight' disadvantage to force a separate http request for this file, if it's packaged properly, the file size will be smaller than the uncompressed code you've included in that file.
It is also normal to have script tags further down in your page that provide extra functionality (ie look at google analytics)
Whenever you are violating the DRY principle (Don't Repeat Yourself), you need to ask why. If you don't have a good reason, then you probably shouldn't be doing it that way.

Is there a good way to prevent jQuery from being redefined?

I encountered a problem that took me some time to debug where a plug-in that I was using for jQuery (in this case jFeed) was not working. The problem ended up being because we also used Amazon Associates product previews. The product previews code ends up including a number of other JS files through document.write(), including another copy of jQuery. Because the product previews code appeared below the jFeed script, jQuery was redefined without the getFeed function.
Is there a best practice to ensure that certain objects like jQuery only get defined once on a page? I'm thinking of something like #ifndef with C/C++, but I don't know how it would work in this case where I didn't write the code that dynamically pulled in jQuery again.
I think in your situation, it would probably be best to redefine the jQuery variable as something else. The other jQuery code might use a different version so you might want to define a new variable which would indicate which jQuery you're using.
You could so something like this:
<script>
var $jMain = jQuery;
</script>
You would then just use the $jMain instead of jQuery or $. It'll be up to you to you to ensure you have the correct jQuery object when you do this. Here's the documentation.
Unfortunately the environment inside one JS sandbox (like within a window or frame of a browser) was not really designed to support the modern world of pulling in scripts from various places; there's no way you can say "define this object and make it resistant to redefinition". (You can even redefine most of the Javascript built-ins if you try!)
Your best shot is to make sure that your code is eval'd last, which gives you final say over the state of the environment when it runs. That doesn't mean other code can't come along later and clobber your definitions, but that's generally really bad form. You can do this by having your script tag be the last element in the body of the document, for example.
See also this jQuery method, which won't help you directly, but gets you thinking about some solutions to page sharing: http://api.jquery.com/jQuery.noConflict/

Where to put JavaScript configuration functions?

What is the general developer opinion on including javascript code on the file instead of including it on the script tag.
So we all agree that jquery needs to be included with a script file, like below:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
My question is, in order to get functions on a page that is not on all pages of a site. Do we include the functions like below in the same page or in a global include file like above called mysite.js.
$(document).ready(function(){
$(".clickme").click(function(event){
alert("Thanks for visiting!");
});
});
ok. So the question is: if the code above is going to be called in every class="clickme" on a specific pages, and you have the ability to call it either from an include separate file called mysite.js or in the content of the page. Which way will you go?
Arguments are:
If you include it on the page you will only call it from those specific pages that the js functionality is needed.
Or you include it as a file, which the browser cached, but then jquery will have to spend x ms to know that that function is not trigger on a page without "clickme" class in it.
EDIT 1:
Ok. One point that I want to make sure people address is what is the effect of having the document.ready function called things that does not exist in the page, will that trigger any type of delay on the browser? Is that a significant impact?
First of all - $("#clickme") will find the id="clickme" not class="clickme". You'd want $(".clickme") if you were looking for classes.
I (try to) never put any actual JavaScript code inside my XHTML documents, unless I'm working on testing something on a page quickly. I always link to an external JS file to load the functionality I want. Browsers without JS (like web crawlers) will not load these files, and it makes your code look much cleaner to the "view source".
If I need a bit of functionality only on one page - it sometimes gets its own include file. It all depends on how much functionality / slow selectors it uses. Just because you put your JS in an external JS file doesn't mean you need to include it on every page.
The main reason I use this practice - if I need to change some JavaScript code, it will all be in the same place, and change site wide.
As far as the question about performance goes- Some selectors take a lot of time, but most of them (especially those that deal with ID) are very quick. Searching for a selector that doesn't exist is a waste of time, but when you put that up against the wasted time of a second script HTTP request (which blocks the DOM from being ready btw), searching for an empty selector will generally win as being the lesser of the two evils. jQuery 1.3 Performace Notes and SlickSpeed will hopefully help you decide on how many MS you really are losing to searching for a class.
I tend to use an external file so if a change is needed it is done in one place for all pages, rather than x changes on x pages.
Also if you leave the project and someone else has to take over, it can be a massive pain to dig around the project trying to find some inline js.
My personal preference is
completely global functions, plugins and utilities - in a separate JavaScript file and referenced in each page (much like the jQuery file)
specific page functionality - in a separate JavaScript file and only referenced in the page it is needed for
Remember that you can also minify and gzip the files too.
I'm a firm believer of Unobtrusive JavaScript and therefore try to avoid having any JavaScript code in with the markup, even if the JavaScript is in it's own script block.
I agreed to never have code in your HTML page. In ASP.net I programmatically have added a check for each page to see if it has a same name javascript file.
Eg. MyPage.aspx will look for a MyPage.aspx.js
For my MVC master page I have this code to add a javascript link:
// Add Each page's javascript file
if (Page.ViewContext.View is WebFormView)
{
WebFormView view = Page.ViewContext.View as WebFormView;
string shortUrl = view.ViewPath + ".js";
if (File.Exists(Server.MapPath(shortUrl)))
{
_clientScriptIncludes["PageJavascript"] = Page.ResolveUrl(shortUrl);
}
}
This works well because:
It is automagically included in my files
The .js file lives alongside the page itself
Sorry if this doesn't apply to your language/coding style.

Categories

Resources