Javascript 使用office js提高Microsoft Word搜索性能

Javascript 使用office js提高Microsoft Word搜索性能,javascript,office-js,Javascript,Office Js,我有下面的代码来搜索文档中的某个段落中的某些文本,如果找到任何出现的文本,请选择第一个 function navigateToWord(paragraphId, text){ Word.run(function (context) { var ps = context.document.body.paragraphs; context.load(ps, 'items'); return context.sync()

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

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 Desktop的性能稍好一些。我怎样才能改进它


我计划多次使用不同的输入参数调用此代码,是否有办法缓存加载的属性,以便第二次调用同一代码时,我不必等待太久?

您加载的内容远远超出了您的需要。首先是一个次要问题:在load命令中指定“items”是不必要的当您拥有集合对象的context.load时,将自动加载项。所以context.loadps是“items”;等同于context.loadps;更重要的是,通过不指定任何其他属性,“加载”默认为加载包括文本在内的所有属性,因此您所有段落的所有文本都将通过连接。最佳做法是在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);
        });

    });
}

非常感谢。你真的帮了我-现在快多了。