简体   繁体   English

外部js文件彼此不认识

[英]external js-files don't know each other

I have a very long external JS-file which I want to split in 2 seperate JS-files. 我有一个很长的外部JS文件,我想分成2个单独的JS文件。 The problem with this is, that file_1.js doesn't know the functions of file_2.js anymore. 问题是, file_1.js不再知道file_2.js的功能。 Is there something special I don't have in mind when I'm doing this. 在执行此操作时,有什么我没想到的东西吗?

<script src="js/file_1.js"></script>
<script src="js/file_2.js"></script>

head of my html. 我的html的头。

and I'm loading every content in a document ready. 我正在将所有内容加载到文档中。

$(function() { some code in both });

Cheers 干杯

Javascript files can only access code from files that are loaded before them. Javascript文件只能访问之前加载的文件中的代码。 In this example file2 can access functions in file1, but not the other way around. 在此示例中,file2可以访问file1中的函数,但不能相反。

If they each need to access each other, you have a circular dependency. 如果他们每个人都需要互相访问,则您具有循环依赖关系。 When this happens, it usually means your two files should really just be one big one. 发生这种情况时,通常意味着您的两个文件实际上应该只是一个大文件。

As previously stated, calling the external js file which declares the functions before the external js which calls the functions is what you need to do. 如前所述,您需要做的是在调用函数的外部js之前调用声明函数的外部js文件。

Have you tried calling one of the functions from within the dom? 您是否尝试过从dom内部调用功能之一? If that fails as well, there may be issues with how you broke up the js. 如果同样失败,则可能是您如何拆分js的问题。

<script src="js/file_2.js"></script>
<script src="js/file_1.js"></script>

vs VS

<script src="js/file_2.js"></script>
<script>
    $(document).ready(function(){
         someFunctionWithinFile_2();
    });
</script>

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

相关问题 UserControl调用JS文件,但似乎没有被调用 - UserControl calling JS-files but they don't seem to get called ES6中的Javascript类,如何将其导入其他js文件和html文件中? - Javascript classes in ES6, how to import them within other js-files and in html files? 如何使用 Angular 8 在 TypeScript 中访问 JavaScript 内容(或扩展其他 JS 文件的 JavaScript 文件) - How to access JavaScript content (or JavaScript files extending other JS-Files) in TypeScript by using Angular 8 如何在不破坏任何功能的情况下使用 barba.js 运行其他 JS 文件 - How to run other JS-files with barba.js with out breaking any functions 将小型js文件合并为一个较大的文件 - Merge small js-files into one bigger 将非NODE_ENV变量从gulpfile传递到其他js文件 - Passing the non-NODE_ENV variables from gulpfile to other js-files 为什么浏览器无法从`../ lib /`(相对)位置找到js文件? - Why browser can't find the js-files from the `../lib/` (relative) location? Browserify-rails无法加载包含JSX的js文件 - Browserify-rails can't load js-files containing JSX Visual Studio Code 不会将 CSS 样式表和 JS 文件添加到 HTML 代码 - Visual Studio Code doesn't add CSS Stylesheets and JS-Files to HTML code Ember.js-在某些模板中加载其他.js文件 - Ember.js - Loading additional .js-Files in some templates
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM