README
DOM Script Injector
Inject/remove scripts, stylesheets and jsonld in html documents.
Install
npm i dom-scripter
Import
Require or import:
const {DomScripter} = require('dom-scripter')
// or
import {DomScripter} from 'dom-scripter'
Or inject via <script>
tag:
<script src="https://cdn.jsdelivr.net/npm/dom-scripter@4/dist/dom-scripter.iife.js" crossorigin type="text/javascript"></script>
Accessible at window.DomScripter
.
Usage
Simply:
const domscripter = new DomScripter()
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 waitForGlobal
so promise will resolve when window.[waitForGlobal]
variable is available.
await domscripter.injectjs(url, {id: 'someid', global: '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 🐬