我有以下代码来搜索文档中的段落中的某些文本,如果找到任何文本,则选择第一个文本。
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 的性能稍好一些)。我该如何改进它?
我计划多次调用此代码(使用不同的输入参数),有没有办法缓存加载的属性,以便我第二次调用相同的代码时,我不知道不用等那么久吗?
最佳答案
您加载的内容超出了您的需要。首先是一个小问题:在加载命令中指定“items”是不必要的。当您有集合对象的 context.load 时,会自动加载“items”。所以 context.load(ps, 'items');
相当于 context.load(ps);
更重要的是,通过不指定任何其他属性,load 默认为 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);
});
});
}
关于javascript - 使用 Office-js 提高搜索 Microsoft Word 的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101059/