简体   繁体   English

优化jQuery速度

[英]Optimizing jQuery speed

I am trying to use jQuery's fancy autocomplete function but I have a problem with speed of executing my script. 我正在尝试使用jQuery的自动完成功能,但是执行脚本的速度存在问题。 Code snippet: 程式码片段:

var data =  <?php if(isset($names)) { echo json_encode(implode(" | ", array_unique($names))); } else { echo "null"; } ?>;
if (data != null) {
    data = data.split(" | ");
    $("#search_names").autocomplete(data);
}

My data comes from some MySQL table and is processed by PHP before jQuery pass it to input field. 我的数据来自某个MySQL表,并在jQuery将其传递到输入字段之前由PHP处理。 When I view source of such page there's enormous amount of text there (obviously) and the page itself loads between 5-10 seconds... 当我查看此类页面的来源时,那里(显然)有大量文本,并且页面本身加载5-10秒之间...

So I wonder is there a way to speed up my script somehow? 所以我想知道是否有某种方式可以加快我的脚本速度? I understand that there will be always so much text to process, whether in same file or in some other included file, but I just wonder am I stuck with 10sec loading page because of so much data or can I somehow make it more awesome? 我知道无论是在同一个文件中,还是在其他包含的文件中, 总会有太多文本要处理,但是我只是想知道由于数据太多,我是否只能停留10秒的加载页面,还是可以以某种方式使其变得更出色? :) :)

Thanks for any help! 谢谢你的帮助!

You should definitely use the remote autocomplete mechanism instead of filling all the data into the document every time. 您绝对应该使用远程自动完成机制,而不是每次都将所有数据填充到文档中。

The first argument can be an URL for remote data or an an array for local data. 第一个参数可以是用于远程数据的URL或用于本地数据的数组。

For remote data: When the user starts typing, a request is send to the specified backend ("my_autocomplete_backend.php"), with a GET parameter named q that contains the current value of the input box and a parameter "limit" with the value specified for the max option. 对于远程数据:当用户开始键入内容时,请求将发送到指定的后端(“ my_autocomplete_backend.php”),该请求带有一个名为q的GET参数,该参数包含输入框的当前值,一个带有该值的参数“ limit”为max选项指定。

if the lookups still take a lot of time, you will probably need to look into optimizing your PHP script instead of the jQuery part. 如果查找仍然花费大量时间,则可能需要考虑优化PHP脚本而不是jQuery部分。 Things like is the database using indexes, etc.... 诸如使用索引等的数据库之类的东西。

Looks like your using the following scritp: http://docs.jquery.com/Plugins/autocomplete 看起来像您使用以下脚本: http ://docs.jquery.com/Plugins/autocomplete

You should be using Ajax for this sort of thing, example: 您应该将Ajax用于此类事情,例如:

 $("#search_names").autocomplete('/ajax/autocomplete.php');

and then within your auto complete html you should do something like: 然后在您的自动完成html中,您应该执行以下操作:

<?php
    //Database
    //Do Query: SELECT item FROM content WHERE {$escaped_q} ORDER BY item_hits DESC LIMIT {$escaped_limit}

   //echo json_encode($results);
?>

Print the results as a JSON Object and it should work MUCH MUCH Faster. 将结果打印为JSON对象,它应该能以更快的速度工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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