0

In the C programming language, there's an include guard which prevents the same header file being included twice:

#ifndef GRANDPARENT_H
#define GRANDPARENT_H

struct foo {
    int member;
};

#endif /* GRANDPARENT_H */

In web pages, JavaScript is often used as a header file, too. Sometimes a developer can mistakenly include the same file twice, causing bugs that are hard to debug (examples here).

The proper way to prevent multiple includes of the same file should be an include guard. But what is the proper way to add such a guard to a JavaScript file so that it works without polluting namespace, breaking other script and other unwanted behavior?


This question is not a duplicate of that question, which doesn't talk about the potential problems of using such a guard. Furthermore, it points to another library, while a lightweight, inline solution would be much more welcome.

Cyker
  • 9,946
  • 8
  • 65
  • 93
  • 1
    *"In web pages, JavaScript is often used as a header file, too."* – That statement makes little sense…!? – deceze Aug 01 '18 at 09:00
  • @deceze If you write JavaScript inside a ` – Cyker Aug 01 '18 at 10:00
  • *Header files*, as in C .h files, are something entirely different than putting a `script` element into an HTML `` element. – deceze Aug 01 '18 at 10:01

1 Answers1

1

The most modular, reusable and "safe" method is simply that including a file shouldn't do anything besides defining some objects/classes/names. If you include a file multiple times, it simply overwrites the previous definition. You then have one entry point somewhere which explicitly starts the code, e.g.:

<body onload="myscript.foo()">

The same goes for includes within Javascript (typically needing a build/bundle system):

import foo from 'bar';
const foo = require('bar');

foo();
deceze
  • 510,633
  • 85
  • 743
  • 889