DOM Script Injector
Injects/removes scripts, stylesheets and jsonld in html documents.
Install
npm i dom-scripter
Import
// cjs
const {domScripter} = require('dom-scripter')
// es
import {domScripter} from 'dom-scripter'
// script tag, window.DomScripter
<script src="https://cdn.jsdelivr.net/npm/dom-scripter@4/dist/dom-scripter.iife.js" crossorigin type="text/javascript"></script>
Usage
Simply:
const elemid = await domScripter.injectJs(url)
// <script type="text/javascript" src="url" id="elemid" async></script>
// element id is auto generated
With attributes:
const elemid = await domScripter.injectJs(url, {
id: 'someid',
attrs: {
'data-name': 'value'
}
})
// <script type="text/javascript" src="url" id="elemid" data-name="value" async></script>
// element id is "someid"
Disable async loading:
await domScripter.injectJs(url, {async: false})
// <script type="text/javascript" src="url" id="elemid"></script>
Inject to different locations (default is bodyEnd
):
await domScripter.injectJs(url, {location: 'headEnd'})
/*
<head>
<title></title>
<script type="text/javascript" src="url" id="elemid" async></script>
</head>
*/
await domScripter.injectJs(url, {location: 'bodyStart'})
/*
<body>
<script type="text/javascript" src="url" id="elemid" async></script>
<p></p>
</body>
*/
await domScripter.injectJs(url, {location: 'bodyEnd'})
/*
<body>
<p></p>
<script type="text/javascript" src="url" id="elemid" async></script>
</body>
*/
Specify waitGlobalVar
so promise will resolve when window.[waitGlobalVar]
variable is available.
await domScripter.injectJs(url, {id: 'someid', waitGlobalVar: 'SomeGlobal'})
// window.SomeGlobal is ready!
Inject stylesheets in the same way:
const elemid = await domScripter.injectCss(url)
// <link id="elemid" rel="stylesheet" href="url">
// element id is auto generated
All of the options above except async is available also for stylesheets.
Inject JSONLD documents in the same way:
const doc = {
"@type":"BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1,
"name": "Home",
"item": "https://example.com"
}
]
}
const elemid = await domScripter.injectJsonLd(doc)
/*
<script type="application/ld+json" id="identifier">
{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://example.com"}]}
</script>
*/
All of the options above except async is available also for JSONLD documents.
To remove an element:
domScripter.remove('identifier')
Version management of this repository done by releaser 🚀
Thanks for watching 🐬