代码之家  ›  专栏  ›  技术社区  ›  Leo

提高使用Office JS搜索Microsoft Word的性能

  •  0
  • Leo  · 技术社区  · 8 年前

    我有下面的代码来搜索文档中的某个段落中的某些文本,如果找到任何匹配项,请选择第一个。

    function navigateToWord(paragraphId, text){
        Word.run(function (context) {
    
            var ps = context.document.body.paragraphs;
            context.load(ps, 'items');
    
            return context.sync()
                .then(function (){
                    let p = ps.items[paragraphId];
    
                    let results = p.search(text);
                    context.load(results, 'items');
    
                    return context.sync().then(function(){
                        if(results.items.length>0){
                            results.items[0].select();
                        }
                    }).then(context.sync);
                });
    
        });
    }
    

    这是可行的,但速度非常慢,尤其是在Word Online上较大的文档上(Word桌面的性能稍好)。我该如何改进?

    我计划多次调用此代码( 输入参数不同 )是否有缓存加载的属性的方法,以便第二次调用相同的代码时,不必等待太长时间?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Rick Kirkham    8 年前

    你装的东西比你需要的多得多。首先是一个要点:不需要在LOAD命令中指定“items”。当您具有集合对象的context.load时,将自动加载项“”。所以 context.load(ps, 'items'); 等于 context.load(ps); 更重要的是,通过不指定任何其他属性,加载默认值为加载所有属性(包括文本),因此所有段落的所有文本都将经过连接。最好在LOAD命令中指定所需的属性。但是,在您的情况下,不需要任何参数,因此应该将一个虚拟字符串作为要加载的第二个参数。这会阻止加载任何属性。以下代码可以工作并且应该更快,尤其是在Word Online中:

    function navigateToWord(paragraphId, text){
      Word.run(function (context) {
    
        var ps = context.document.body.paragraphs;
        context.load(ps, 'no-properties-needed');
    
        return context.sync()
            .then(function (){
                let p = ps.items[paragraphId];
    
                let results = p.search(text);
                context.load(results, 'no-properties-needed');
    
                return context.sync().then(function(){
                    if(results.items.length>0){
                        results.items[0].select();
                    }
                }).then(context.sync);
            });
    
        });
    }