[在执行代码之前检查JS插件是否已加载

问题描述 投票:0回答:1

我想对自己制作的自定义JS插件遇到的一个小问题有所了解。这很简单,我正在使用插件JS模板写出要附加的插件。然后,我将初始化插件,理想情况下,需要先确定是否有办法在执行任何操作之前检查插件JS文件是否已加载:

插件模板

(function() {
  this.MyPlugin = function() {

    // default settings
    const INBOUND_CONFIG = {
      isEnabled: false
    }

    // Create options by extending defaults with the passed in arugments
    if (arguments[0] && typeof arguments[0] === "object") {
      this.options = extendDefaults(INBOUND_CONFIG, arguments[0]);
    }

    // custom public method
    HoneycombInbound.prototype.getSettings = function() {

    }

    // Utility method to extend defaults with user options
    function extendDefaults(source, properties) {
      var property;
      for (property in properties) {
        if (properties.hasOwnProperty(property)) {
          source[property] = properties[property];
        }
      }
      return source;
    }

  }
}());

使用上面的代码,我将按照以下方式初始化HTML中的插件:

<script src="./my-plugin.js"></script>

<script>
  const plugin = new MyPlugin()

  // this doesn't work if the script file isn't linked:
  if (plugin) {
    // do something
  }
</script>

[不幸的是,例如,如果未加载JS文件,对plugin的简单检查实际上不起作用,我什至尝试了类似的事情:if (new MyPlugin()) {},希望渺茫。

我本质上需要一种不会在浏览器中引发错误的方法。我可以使用任何解决方案来在执行之前正确检查它是否已加载吗?

javascript html ecmascript-6 plugins ecmascript-5
1个回答
0
投票

对我有用的解决方案是使用WebAPI postMessage

我曾经与客户端通信,插件已准备就绪。

因此,在plugin上,您将需要以下内容:

window.postMessage("The plugin is ready to go" );

并且在您的client上,您需要添加一个新的侦听器来捕获消息:

window.addEventListener("message", myMessage, false);

const myMessage = (event) => {
  if (event.data === "The plugin is ready to go")
  // This is your message so do your stuff here
  ...
}

编辑

因此,要实现此行为,您将需要在客户端启用初始化:

const myPlugin = {
  init: () => { 
    // Initilize the plugin if you are using the DOM you can add a parameter with an id to mount it whenever you need it
    //Otherwise just configure or initilize the variables that you will use 
    // And here you need to pass the messsage to tell the client that everyting is ready
    // Here you need to configure the origin correctly depending on your needs check the documentation for more details 
    window.addEventListener("message", myMessage, false);
  },
  someFunctionality: () => {
    //This pattern is to expose the funtionalities to the client so you can achieve any
  }
}; 

所以现在在您的客户端上,您只需要添加脚本并告诉插件进行初始化:

<script type='text/javascript' src='/myPlugin.js'></script>
<script>
 window.addEventListener("message", myMessage, false);

 const myMessage = (event) => {
   if (event.data === "The plugin is ready to go")
   // This is your message so do your stuff here
   ...
 }
 myPlugin.init();

</script>
© www.soinside.com 2019 - 2024. All rights reserved.