include()

include() loads and executes another JavaScript file in the same context. Variables, functions, and state from the included file are accessible afterward.

Syntax

include(path)

Parameters

ParameterTypeDescription
pathstringPath to a .js file, relative to the current script

Return Value

None (undefined). Throws an error if the file cannot be found.

Examples

Shared Layout

// header.js
print("<html><head><title>My Site</title></head><body>");
print("<nav>...</nav>");
// footer.js
print("<footer>&copy; 2026</footer>");
print("</body></html>");
// index.js
include("./includes/header.js");
print("<h1>Welcome</h1>");
include("./includes/footer.js");

Shared Variables

// config.js
var siteName = "My App";
var version = "1.0.0";
// index.js
include("./config.js");
print(`<title>${siteName} v${version}</title>`);

Path Resolution

  • ./file.js — relative to the main script's directory
  • ./lib/helpers.js — subdirectory
  • /var/www/js/shared/common.js — absolute path

include() vs ES Modules

Featureinclude()import/export
Shares scopeYesNo (isolated)
Can output HTMLYesNot directly
Best forTemplates, layoutsLibraries, utilities
ExecutionImmediate, inlineModule evaluation

Errors

If the file does not exist, an error is thrown:

// Throws: Cannot include './missing.js': file not found
include("./missing.js");
Was this page helpful?