Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require_once like for javascript ?

Tags:

javascript

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

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

Are they solution for this ?

like image 679
Sindar Avatar asked Mar 01 '11 13:03

Sindar


People also ask

What does require () do in JavaScript?

require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.

How add require in JavaScript?

To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.

What is difference between require and require_once in php?

The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.

How does require_once work in PHP?

The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.


2 Answers

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

like image 110
Andrew Hare Avatar answered Oct 23 '22 14:10

Andrew Hare


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

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.

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

like image 44
Jakob Avatar answered Oct 23 '22 15:10

Jakob