How I Refactored My Widget Embed Code: From 8 Lines of JavaScript to a Single Data Attribute
Source: Dev.to
Original Embed Code
document.addEventListener('DOMContentLoaded', function () {
init('da0a042d-78b7-4b0b-98b6-bc05a8c119c4');
});
The embed consisted of two parts:
-
External resource loader
-
Initialization snippet
document.addEventListener(‘DOMContentLoaded’, function () { init(‘da0a042d-78b7-4b0b-98b6-bc05a8c119c4’); });
While functional, this approach required pasting two separate script blocks.
## Simplified Widget Implementation
A minimal `widget.js` can expose an `init` function:
```js
(function () {
window.init = function (x) {
const container = document.createElement('div');
container.textContent = x;
document.body.appendChild(container);
};
})();
The init function receives an identifier, creates a “ with that value, and appends it to the page. In a real widget the ID would be used to fetch settings (color, position, etc.) from a backend.
The Solution: Auto‑Initialization
To allow a single‑tag embed, the script reads a data-id attribute from its own <script> element and calls init automatically.
function autoInit() {
const scriptTag = document.querySelector('script[src*="widget.js"][data-id]');
if (scriptTag) {
window.init(scriptTag.dataset.id);
}
}
document.addEventListener('DOMContentLoaded', autoInit);
With this logic, the embed becomes:
Final widget.js
(function () {
window.init = function (x) {
const container = document.createElement('div');
container.textContent = x;
document.body.appendChild(container);
};
function autoInit() {
const scriptTag = document.querySelector('script[src*="widget.js"][data-id]');
if (scriptTag) {
window.init(scriptTag.dataset.id);
}
}
document.addEventListener('DOMContentLoaded', autoInit);
})();
Conclusion
By consolidating the embed into a single <script> tag with a data-id attribute, the implementation becomes cleaner and more user‑friendly. Users now only need to add one line of code, reducing complexity, potential errors, and giving the widget a more polished, professional feel—much like other widely‑used third‑party solutions.