简体   繁体   English

如何加载通过JavaScript对象调用的JavaScript文件的功能

[英]How do I load the functions of a JavaScript File called through a JavaScript Object

I have a local JS file that needs to be called using a script object. 我有一个本地JS文件,需要使用脚本对象调用该文件。 However, I am not able to get the functions to run. 但是,我无法运行这些功能。 Here's the code snippet. 这是代码片段。

<script type="text/javascript">
 var x = document.createElement("SCRIPT");
 x.type = "text/javascript";
 x.src = "file:///C:/scripts/localscript.js";
 //one of the functions is loadData();
 loadData(); //I'm getting reference error, loadData is not defined.
</script>

Thank you, 谢谢,

You need to create a script element and insert it in DOM (mostly under head) to load the script. 您需要创建一个script元素并将其插入DOM (mostly under head)以加载脚本。 When that script is loaded by the browser, whatever you return from that script will be available. 当浏览器加载该脚本时,从该脚本返回的任何内容都将可用。

Consider sampleScript.js with below code 考虑以下代码的sampleScript.js

(function(window){
  'use strict';

  window.app = {
    sayHi: function() {
      console.log('Hey there !');
    }

  };

})(this);

To load this script, I do 要加载此脚本,我要做

<script>
   var node = document.createElement('script');
   node.src = 'sampleScript.js';
   node.addEventListener('load', onScriptLoad, false);
   node.async = true;
   document.head.appendChild(node);

   function onScriptLoad(evt) {
     console.log('Script loaded.');
     console.log('app.sayHi ---> ');
     app && app.sayHi();
   }
</script>

Taking cues, you can fit to your need. 提示,您可以满足自己的需求。 Hope this helps. 希望这可以帮助。

使用onload事件:

x.onload = function() { window.loadData(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM