require_once 就像 javascript 一样?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5154915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:11:11  来源:igfitidea点击:

require_once like for javascript ?

javascript

提问by Sindar

I'm currently searching a solution to not include two times the same .js

我目前正在寻找不包含两次相同 .js 的解决方案

So my question is relatively simple, i'm searching something like requice_once (.php) or #ifndef(.c/.c++).

所以我的问题相对简单,我正在搜索类似 requice_once (.php) 或 #ifndef(.c/.c++) 的内容。

Are they solution for this ?

他们是解决方案吗?

采纳答案by Andrew Hare

I would suggest that you use either require.jsor head.jsfor this kind of thing. They are fully-featured and provide performance benefits as well.

我建议你使用require.jshead.js来处理这种事情。它们功能齐全,还提供性能优势。

回答by Jakob

You can write your own ifndef-code, just write your files like this (assuming it's for a browser):

您可以编写自己的 ifndef 代码,只需像这样编写文件(假设它是用于浏览器的):

if (!window.NAME_UNIQUE_FOR_THIS_FILE) {
  window.NAME_UNIQUE_FOR_THIS_FILE = true;

  .. your code here ...

}

The if-statement checks if the uniquely named variable exists already. If not, create it (so the next time this code is seen, it will be ignored). Then run whatever you want this file to do.

if 语句检查唯一命名的变量是否已经存在。如果没有,则创建它(这样下次看到此代码时,它将被忽略)。然后运行您希望此文件执行的任何操作。

Be sure to use a veryunique name though, since it's a global variable.

不过一定要使用一个非常独特的名称,因为它是一个全局变量。