6

SharePoint Modern Page 的脚本引入部件

 2 years ago
source link: https://www.cnblogs.com/jianyus/p/15823245.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

SharePoint Modern Page 的脚本引入部件

  前言

  霖雨之前无聊,分享了一下自己闲暇之余开发的一个脚本引用的部件,专门为Modern页面使用。

  这里,也简单介绍一下webpart的逻辑,大家可以看看。

  正文

  1.首先,页面要引用一个加载JavaScript库的方法和一个自定义的CSS,如下:

import { SPComponentLoader } from '@microsoft/sp-loader';
require("./asset/Injection.css");

  2.整个功能非常非常非常简单,好吧,就是在页面上插入一个空的DIV,然后,有一个引入脚本的功能:

public render(): void {
  let ZoneId = this.properties.ZoneId,
    ImgSrc = require<string>('./asset/loading.gif'),
    Mesg = `<div id="linyuLoading"><div id="linyuLoadingImg"><img src="${ImgSrc}"></img></div><div id="linyuLoadingText">loading</div></div>`;

    Mesg = "<div id='linyuWarning'>Please configure \"Zone Id\" in WebPart Properties</div>";

  this.domElement.innerHTML = `<div id="${ZoneId}">${Mesg}</div>`;
  console.log("123");


  if (this.properties.JavaScirptLink != "")
    SPComponentLoader.loadScript(this.properties.JavaScirptLink);
}

  3.然后,就是添加右侧webpart属性,如下:

protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
  return {
    pages: [
      {
        groups: [
          {
            groupName: "WebPart Properties",
            groupFields: [
              PropertyPaneTextField('ZoneId', {
                label: "Zone Id",
                description: "Please enter your Zone Id"
              }),
              PropertyPaneTextField('JavaScirptLink', {
                label: "JavaScirpt Link",
                description: "Please enter your JavaScript file reference URL",
              })
            ]
          }
        ]
      }
    ]
  };
}

  4.再有就是一个引入图片的方法:

let ImgSrc = require<string>('./asset/loading.gif')

  5.整个解决方案的功能非常简单,最初的想法就是在Modern页面中加入一个占位的Div,其ID可以配置,然后引入脚本就可以了。

  整个功能就是通过引入的脚本去获取数据,处理数据,然后填充到占位的DIV中就可以了。

  然后,代码调试的时候碰到一个问题,就是引入脚本过程是异步的,经常有脚本引入没完成,就执行下面的方法了。

  所以,下面一段代码很重要,其作用就是先引入脚本,等待脚本加载完毕执行回调函数。

function loadScript(url,callback){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild(script);

    if(script.readyState){
        script.onreadystatechange = function(){
            if(script.readyState == 'loaded' || script.readyState == 'complete'){
                script.onreadystatechange = null;
                callback();
            }
        }
    }else{
        script.onload = function(){
            callback();
        }
    }
}

  结束语

  在使用SharePoint Modern 页面中,无法定制化一直是一个大问题,然后,很多人都不具备SharePoint Framework的开发能力。

  这样一个开源的webpart大家可以尝试一下,也许会对大家使用SharePoint Online Modern页面有所帮助。

  Github:linyus/LinyuInjectionScriptWebpart (github.com)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK