@swup/scripts-plugin
Version:
A swup plugin for re-evaluating scripts
1 lines • 2.88 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import Plugin from '@swup/plugin';\n\nexport type Options = {\n\thead: boolean;\n\tbody: boolean;\n\toptin: boolean;\n};\n\nexport default class SwupScriptsPlugin extends Plugin {\n\tname = 'SwupScriptsPlugin';\n\n\trequires = {\n\t\tswup: '>=4'\n\t};\n\n\tdefaults: Options = {\n\t\thead: true,\n\t\tbody: true,\n\t\toptin: false\n\t};\n\n\toptions: Options;\n\n\tconstructor(options: Partial<Options> = {}) {\n\t\tsuper();\n\t\tthis.options = { ...this.defaults, ...options };\n\t}\n\n\tmount() {\n\t\tthis.on('content:replace', this.runScripts);\n\t}\n\n\trunScripts() {\n\t\tconst { head, body, optin } = this.options;\n\t\tconst scope = this.getScope({ head, body });\n\t\tif (!scope) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst selector = optin\n\t\t\t? 'script[data-swup-reload-script]'\n\t\t\t: 'script:not([data-swup-ignore-script])';\n\n\t\tconst scripts = Array.from(scope.querySelectorAll<HTMLScriptElement>(selector));\n\t\tscripts.forEach((script) => this.runScript(script));\n\n\t\tthis.swup.log(`Executed ${scripts.length} scripts.`);\n\t}\n\n\trunScript(script: HTMLScriptElement) {\n\t\tconst element = document.createElement('script');\n\t\tfor (const { name, value } of script.attributes) {\n\t\t\telement.setAttribute(name, value);\n\t\t}\n\t\telement.textContent = script.textContent;\n\t\tscript.replaceWith(element);\n\n\t\treturn element;\n\t}\n\n\tgetScope({ head, body }: Pick<Options, 'head' | 'body'>) {\n\t\tif (head && body) return document;\n\n\t\tif (head) return document.head;\n\n\t\tif (body) return document.body;\n\n\t\treturn null;\n\t}\n}\n"],"names":["Plugin","constructor","options","super","this","name","requires","swup","defaults","head","body","optin","mount","on","runScripts","scope","getScope","scripts","Array","from","querySelectorAll","forEach","script","runScript","log","length","element","document","createElement","value","attributes","setAttribute","textContent","replaceWith","_ref"],"mappings":"qIAQqB,cAA0BA,EAAM,QAepDC,WAAAA,CAAYC,QAAAA,IAAAA,IAAAA,EAA4B,CAAA,GACvCC,QAAQC,KAfTC,KAAO,oBAEPC,KAAAA,SAAW,CACVC,KAAM,OACNH,KAEDI,SAAoB,CACnBC,MAAM,EACNC,MAAM,EACNC,OAAO,QAGRT,aAAO,EAINE,KAAKF,QAAU,IAAKE,KAAKI,YAAaN,EACvC,CAEAU,KAAAA,GACCR,KAAKS,GAAG,kBAAmBT,KAAKU,WACjC,CAEAA,UAAAA,GACC,MAAML,KAAEA,EAAIC,KAAEA,EAAIC,MAAEA,GAAUP,KAAKF,QAC7Ba,EAAQX,KAAKY,SAAS,CAAEP,OAAMC,SACpC,IAAKK,EACJ,OAGD,MAIME,EAAUC,MAAMC,KAAKJ,EAAMK,iBAJhBT,EACd,kCACA,0CAGHM,EAAQI,QAASC,GAAWlB,KAAKmB,UAAUD,IAE3ClB,KAAKG,KAAKiB,IAAgB,YAAAP,EAAQQ,kBACnC,CAEAF,SAAAA,CAAUD,GACT,MAAMI,EAAUC,SAASC,cAAc,UACvC,IAAK,MAAMvB,KAAEA,EAAIwB,MAAEA,KAAWP,EAAOQ,WACpCJ,EAAQK,aAAa1B,EAAMwB,GAK5B,OAHAH,EAAQM,YAAcV,EAAOU,YAC7BV,EAAOW,YAAYP,GAEZA,CACR,CAEAV,QAAAA,CAAQkB,GAA+C,IAA9CzB,KAAEA,EAAIC,KAAEA,GAAsCwB,EACtD,OAAIzB,GAAQC,EAAaiB,SAErBlB,EAAakB,SAASlB,KAEtBC,EAAaiB,SAASjB,SAG3B"}