简体   繁体   中英

How do I make this popup code cleaner?

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()}
}

<a href="song-lyrics.txt" onclick="return popitup('song-lyrics.txt')"></a>

Is there a cleaner way to write this? Also, how do I make the scrollbar appear?

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.

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();
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM