diff --git a/src/htmx.d.ts b/src/htmx.d.ts index 4b0fab7a2..85310b140 100644 --- a/src/htmx.d.ts +++ b/src/htmx.d.ts @@ -129,6 +129,13 @@ export function findAll(selector: string): NodeListOf; */ export function findAll(elt: Element, selector: string): NodeListOf; +/** + * When htmx is imported as a module, this function must be called to initialize it. + * + * https://htmx.org/api/#start + */ +export function start(): void; + /** * Log all htmx events, useful for debugging. * @@ -288,6 +295,8 @@ export function values(elt: Element, requestType?: string): any; export const version: string; export interface HtmxConfig { + /** whether or not htmx should be initialized automatically when DOM is ready */ + autoStart?: boolean; /** array of strings: the attributes to settle during the settling phase */ attributesToSettle?: ["class", "style", "width", "height"] | string[]; /** if the focused element should be scrolled into view */ diff --git a/src/htmx.js b/src/htmx.js index 54b0e9d6b..5f7bb429e 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -23,6 +23,7 @@ return (function () { //** @type {import("./htmx").HtmxApi} */ // TODO: list all methods in public API var htmx = { + start: start, onLoad: onLoadHelper, process: processNode, on: addEventListenerImpl, @@ -47,6 +48,7 @@ return (function () { logNone : logNone, logger : null, config : { + autoStart: document.currentScript !== null, // do not initialize htmx automatically if executed as module historyEnabled:true, historyCacheSize:10, refreshOnHistoryMiss:false, @@ -2102,6 +2104,14 @@ return (function () { } } + function logWarn(msg) { + if(console.warn) { + console.warn(msg); + } else if (console.log) { + console.log("WARN: ", msg); + } + } + function triggerEvent(elt, eventName, detail) { elt = resolveTarget(elt); if (detail == null) { @@ -3633,22 +3643,34 @@ return (function () { } } + var metaConfigLoaded = false; function mergeMetaConfig() { + if (metaConfigLoaded) { + return; + } + var metaConfig = getMetaConfig(); if (metaConfig) { htmx.config = mergeObjects(htmx.config , metaConfig) } + metaConfigLoaded = true; } - // initialize the document - ready(function () { + var started = false; + function start() { + if (started) { + logWarn('htmx has already been initialized on this page. Calling htmx.start() more than once may cause problems.'); + } + started = true; + + var body = getDocument().body; + if (!body) { + logError('Unable to initialize. Trying to load htmx before `` is available. Did you forget to add `defer` in htmx\'s `