编程小贴士

给你的编程提供小点子


15个Javascript优化小技巧总结

JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。

不 仅如此,JavaScript还是很多新手踏入编程世界的第一个语言。既可以用来显示浏览器中的简单提示框,也可以通过nodebot或nodruino 来控制机器人。能够编写结构清晰、性能高效的JavaScript代码的开发人员,现如今已成了招聘市场最受追捧的人。

在这篇文章中,小编将为大家分享一些JavaScript的技巧、秘诀和最佳实践。不管是浏览器的JavaScript引擎,还是服务器端JavaScript解释器,均适用。

1. 使用===取代==

==和!=操作符会在需要的情况下自动转换数据类型。但===和!==不会,它们会同时比较值和数据类型,这也使得它们要比==和!=快。

[10] === 10 // is false
[10] == 10 // is true
'10' == 10 // is true
'10' === 10 // is false
 == 0 // is true
 === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false

2. 使用对象构造器

function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");

3. 使用自调用函数

函数在创建之后直接自动执行,通常称之为自调用匿名函数(Self-Invoked Anonymous Function)或直接调用函数表达式(Immediately Invoked Function Expression )。格式如下:

(function{
// 置于此处的代码将自动执行
});
(function(a,b){
var result = a+b;
return result;
})(10,20)

4. 通过for-in循环检查对象的属性

下面这样的用法,可以防止迭代时进入到对象的原型属性中。

for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}

5. 临时存储用于计算和查询的变量

在jQuery选择器中,可以临时存储整个DOM元素。

var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');

6. 避免在数组中使用负数做索引

var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf("foo") ; // from is equal to -1
numbersArray.splice(from,2); // will return [5]

注意:传给splice的索引参数不要是负数,当是负数时,会从数组结尾处删除元素。

7. 不要使用eval或者函数构造器

eval和函数构造器(Function consturctor)的开销较大,每次调用,JavaScript引擎都要将源代码转换为可执行的代码。

var func1 = new Function(functionCode);
var func2 = eval(functionCode);

8. 避免使用with

使用with可以把变量加入到全局作用域中,因此,如果有其它的同名变量,一来容易混淆,二来值也会被覆盖。

9. 使用switch/case代替一大叠的if/else

当判断有超过两个分支时使用switch/case要更快一些,而且也更优雅,更利于代码的组织,当然,如果有超过10个分支,就不要使用switch/case了。

10. 使用对象作为对象的原型

下面这样,便可以给定对象作为参数,来创建以此为原型的新对象:

function clone(object) {
function OneShotConstructor{};
OneShotConstructor.prototype = object;
return new OneShotConstructor;
}
clone(Array).prototype ; //

11. HTML字段转换函数

function escapeHTML(text) {
var replacements= {"": ">","&": "&", "\"": """};
return text.replace(/[&"]/g, function(character) {
return replacements[character];
});
}

12. 首次为变量赋值时务必使用var关键字

变量没有声明而直接赋值得话,默认会作为一个新的全局变量,要尽量避免使用全局变量。

13. 字符串去空格

Java、C#和PHP等语言都实现了专门的字符串去空格函数,但JavaScript中是没有的,可以通过下面的代码来为String对象函数一个trim函数:

String.prototype.trim = function{return this.replace(/^\s+|\s+$/g, "");};

JavaScript引擎已经有了trim的原生实现。

14. 处理WebSocket的超时

通常情况下,WebSocket连接创建后,如果30秒内没有任何活动,服务器端会对连接进行超时处理,防火墙也可以对单位周期没有活动的连接进行超时处理。

为了防止这种情况的发生,可以每隔一定时间,往服务器发送一条空的消息。可以通过下面这两个函数来实现这个需求,一个用于使连接保持活动状态,另一个专门用于结束这个状态。

var timerID = 0;
function keepAlive {
var timeout = 15000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive {
if (timerId) {
cancelTimeout(timerId);
}
}

15. 开发时注意代码结构,上线前检查并压缩JavaScript代码

别忘了在写代码时使用一个代码美化工具。使用JSLint(一个语法检查工具)并且在上线前压缩代码(比如使用JSMin)。注:现在代码压缩一般推荐 UglifyJS (https://github.com/mishoo/UglifyJS2)

79 Responses to “ 15个Javascript优化小技巧总结 ”

  1. see pron说道:

    m1g6ap Im obliged for the article.Thanks Again. Cool.

  2. Nyla Warnack说道:

    Hmm it appears like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the whole thing. Do you have any suggestions for first-time blog writers? I’d really appreciate it.

  3. I am only writing to make you be aware of of the wonderful experience my friend’s child gained browsing your web page. She came to understand some pieces, including what it’s like to possess a great helping mindset to let many more with no trouble know precisely certain grueling topics. You actually exceeded readers’ expected results. I appreciate you for supplying such warm and friendly, healthy, edifying and in addition fun thoughts on your topic to Julie.

  4. The when I read a weblog, I’m hoping which it doesnt disappoint me about this. Come on, man, Yes, it was my choice to read, but I personally thought youd have something fascinating to say. All I hear is actually a handful of whining about something that you could fix when you werent too busy trying to find attention.

  5. yeezy boost 350说道:

    I precisely wished to say thanks again. I am not sure what I might have implemented without the type of recommendations shown by you on that industry. This was a very scary dilemma for me personally, nevertheless spending time with this specialised mode you treated it forced me to cry over delight. I will be happy for the work and in addition have high hopes you find out what a great job you were providing educating others with the aid of your websites. More than likely you’ve never encountered all of us.

  6. Elin Scala说道:

    I’m new to your blog and i really appreciate the nice posts and great layout..”;.*

  7. see pron说道:

    kGWVDX This blog post is excellent, probably because of how well the subject was developped. I like some of the comments too though I would prefer we all stay on the suject in order add value to the subject!

  8. Thanks so much for the article.Thanks Again. Really Great.

  9. I truly appreciate this blog.Thanks Again. Much obliged.

  10. Guess Romania说道:

    very nice post, very nice post, i certainly love this fabulous website, go on it

  11. porn说道:

    Informative and precise Its hard to find informative and accurate information but here I found

  12. You ave made some good points there. I checked on the net to learn more about the issue and found most individuals will go along with your views on this web site.

  13. Websites we recommend Wow, superb blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is excellent, as well as the content!

  14. Gclub Download说道:

    Thanks-a-mundo for the article post. Great.

  15. time as looking for a similar topic, your website came up, it seems good.

  16. Very nice write-up. I absolutely appreciate this site. Stick with it!

  17. crypto说道:

    Very good information. Lucky me I came across your website by accident (stumbleupon). I ave saved it for later!

  18. tank fit-up bed说道:

    You made some good points there. I checked on the internet for more info about the issue and found most people will go along with your views on this web site.

  19. on your blog. Is this a paid theme or did you modify

  20. This is one awesome blog article.Really looking forward to read more. Will read on

  21. Escorts Miami说道:

    Very good article! We are linking to this particularly great post on our website. Keep up the great writing.

  22. Simply a smiling visitor here to share the love (:, btw great style and design.

  23. Very neat article.Really thank you! Fantastic.

  24. escorts sydney说道:

    It as the little changes which will make the largest changes.

  25. whoah this weblog is great i love reading your posts. Stay

  26. houston escorts说道:

    rest аА аБТ•f the аАаб‚Т€а‚ite аАаб‚Т€Т“аАаб‚Т€а‚ also reаА аЂаlly

  27. Gurgaon说道:

    Some really superb blog posts on this website , thankyou for contribution.

  28. Thank you for your blog post.Thanks Again. Keep writing.

  29. There is certainly a lot to find out about this topic. I like all of the points you have made.

  30. balo nam说道:

    Thanks so much for the blog.Really looking forward to read more. Cool.

  31. 먹튀검증说道:

    I’а†ve read several good stuff here. Certainly value bookmarking for revisiting. I surprise how so much effort you place to create the sort of great informative website.

  32. 먹튀 폴리스说道:

    Some times its a pain in the ass to read what blog owners wrote but this site is very user genial!.

  33. purchase music说道:

    Looking forward to reading more. Great article post.Really looking forward to read more. Really Cool.

  34. Ridiculous quest there. What occurred after? Take care!

  35. cheap mp3说道:

    Very good blog post. I certainly appreciate this site. Stick with it!

  36. cat blog说道:

    Just wanna comment that you have a very nice site, I the style and design it actually stands out.

  37. The Lost Ways说道:

    Thanks for good article. I read it with big pleasure. I look forward to the next article.

  38. Say, you got a nice article. Really Great.

  39. buy mp3说道:

    Im thankful for the blog.Much thanks again. Will read on

  40. generic levitra说道:

    post and the rest of the site is also really good.

  41. Very good blog.Much thanks again. Awesome.

  42. Wow! Thank you! I continuously wanted to write on my website something like that. Can I implement a portion of your post to my site?

  43. Barcode说道:

    pretty beneficial stuff, overall I believe this is well worth a bookmark, thanks

  44. Very interesting information!Perfect just what I was looking for!

  45. Wow, fantastic blog structure! How long have you been running a blog for? you make running a blog glance easy. The total look of your web site is great, let alone the content!

  46. 토토사이트说道:

    Really enjoyed this blog article.Really thank you! Keep writing.

  47. port renfrew说道:

    There is clearly a bunch to realize about this. I feel you made various good points in features also.

  48. 바다이야기说道:

    It as going to be end of mine day, however before end I am reading this wonderful piece of writing to improve my know-how.

  49. 다자바说道:

    Thanks so much for the blog post.Thanks Again. Want more.

  50. Im thankful for the post.Thanks Again. Will read on

  51. Vancouver SEO说道:

    use the web for that purpose, and take the most recent news.

  52. Nonton Anime说道:

    Awseome article, I am a big believer in commenting on blogs and forums to let the blog writers know that they’ve added something of great benefit to the world wide web!

  53. Muchos Gracias for your article post.Really looking forward to read more.

  54. you are truly a excellent webmaster. The site loading speed

  55. superb post.Ne aer knew this, thanks for letting me know.

  56. Say, you got a nice post.Much thanks again. Want more.

  57. Inspiring story there. What occurred after? Take care!

  58. Thanks-a-mundo for the post.Thanks Again. Keep writing.

  59. There is apparently a bundle to know about this. I suppose you made certain good points in features also.

  60. Im grateful for the blog.Really looking forward to read more. Awesome.

  61. Audi Mechanic说道:

    Simply wanna admit that this is invaluable , Thanks for taking your time to write this.

  62. 다잡아说道:

    Your style is really unique in comparison to other people I have read stuff from. I appreciate you for posting when you ave got the opportunity, Guess I all just book mark this page.

  63. 바다 이야기说道:

    Value the admission you presented.. So pleased to possess identified this publish.. Actually effective standpoint, thanks for giving.. sure, research is paying off.

  64. 먹튀 검증说道:

    Thanks-a-mundo for the blog post.Really looking forward to read more. Really Great.

  65. Well My spouse and i definitely enjoyed studying the idea. This idea procured simply by you is very constructive forever planning.

  66. Thanks-a-mundo for the blog.Really thank you! Much obliged.

  67. This tends to possibly be pretty beneficial for a few of the employment I intend to you should not only with my blog but

  68. 토토사이트说道:

    Very good info. Lucky me I came across your blog by chance (stumbleupon). I ave book-marked it for later!

  69. Terrific work! That is the type of information that are meant to be shared around the net. Shame on Google for not positioning this put up higher! Come on over and consult with my site. Thanks =)

  70. Im obliged for the blog post. Really Great.

  71. Thanks for the post.Really thank you! Really Cool.

  72. seo tool说道:

    I value the article post.Really thank you! Keep writing.

  73. we came across a cool web-site which you may possibly appreciate. Take a look when you want

  74. 토토 사이트说道:

    Well I truly enjoyed studying it. This information offered by you is very practical for proper planning.

  75. 바다이야기说道:

    I really liked your blog post. Much obliged.

  76. 다잡아说道:

    Wow! This could be one particular of the most helpful blogs We have ever arrive across on this subject. Basically Magnificent. I am also a specialist in this topic so I can understand your effort.

  77. Very informative blog.Really looking forward to read more. Much obliged.

  78. 우리카지노说道:

    Really informative blog.Really thank you! Cool.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>