简体   繁体   English

外部文件中的函数未定义 [JS]

[英]Function from External file is not defined [JS]

Hello I have a problem with JavaScript function.您好,我的 JavaScript 函数有问题。
I have 3 external JS files that are included to my JS file like that:我有 3 个外部 JS 文件,它们包含在我的 JS 文件中,如下所示:

var badgeJs = document.createElement('script');
badgeJs.type = 'text/javascript';
badgeJs.src = 'url'
document.head.appendChild(badgeJs);

So here is the problem I need to use 3 functions, but sometimes I received error Refference error: functionName is not defined , after that I refresh the page and first function works but second one no, and every time on refresh some of functions are not defined.所以这里是我需要使用 3 个函数的问题,但有时我收到错误Refference error: functionName is not defined ,之后我刷新页面,第一个函数有效,但第二个函数无效,每次刷新时有些函数没有定义。
I don't know what is the problem and why this happen?我不知道是什么问题,为什么会发生这种情况? Any advice will be appreciate.任何建议将不胜感激。
I don't know if this is gonna help but JS code is for a shopify-app我不知道这是否会有所帮助,但 JS 代码适用于shopify-app

How I call functions我如何调用函数


var content = 'function1(param);function2(param1, param2, param3, [10, 25]);function3(param1, param2);';
(function() { var script = document.createElement('script'); script.text = content; var body = document.querySelector('body'); body.append(script);})();

Your file inclusions run at the sime time you're trying to call your functions.您的文件包含在您尝试调用函数的同时运行。 As the file inclusion need time to load your files, you are calling the functions before they have been loaded.由于文件包含需要时间来加载您的文件,因此您在加载之前调用了这些函数。 You have to manually add your scripts to the HTML:您必须手动将脚本添加到 HTML:

<script type="text/javascript" src="/to/your/file.js">

And then run your function when the DOM has been loaded:然后在加载 DOM 后运行您的函数:

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
});

If you can't change the HTML, then include your files dynamically and make sure to call your functions when the files are loaded.如果您无法更改 HTML,则动态包含您的文件并确保在加载文件时调用您的函数。

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

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