I am looking to create a javascript \"widget\" that can be hosted on other sites. For example. I want to host the javascript code on my site:
http://scripts.my
What PatrikAkerstrand said, is totally, 100% right.
What I want to add here, is a framework in vanilla JS that can save you a lot of time and effort to implement it, as everything is thought of, polished, and tested. All is left is to define your own widgets, and use them.
Here's an example of what it looks like.
A widget code// inside a js file of a widget class
(function () {
var Module_Path = ["WidgetsLib", "a1", "Button"];
var curr = this;
Module_Path.forEach(function(i){if (curr[i] == null) {addChildToTree(curr, i, {})} curr = curr[i]});
specialize_with(curr, {
CSS_Literal: `
.{{WIDGET_CLASS_ID}}_Something {
color: hsl(0, 0%, 20%);
}
`,
HTML_Literal: `
<div onclick="{{WIDGET_INSTANCE}}.onclick(event)"
class="{{WIDGET_CLASS_ID}}_Something"
>
SOME SUPER COOL WIDGET
</div>
`,
new: typical_widget_new,
});
})();
An HTML:
<div id="w1" style="background-color: hsl(200, 50%, 50%);"></div>
<script src="WidgetsLib/a1/Button/js"></script>
A user JavaScript code:
var b1 = WidgetsLib.a1.Button.new("w1", {
onclick: function(ev) {
ev.target.style.color = "#ffff00";
console.log("====== HERE");
}
});
Please download, and open the Widget_v2.md.html in a browser, it's https://github.com/latitov/JS_HTML_Widgets .
What you'll get:
And enjoy creating re-usable widgets of your own, of arbitrary complexity, easily!
Your script should not interfere with the rest of the page.
I would try to:
Make it configurable
By doing this you let the user decide if he wants your widget to automatically load the stylesheet, or if he wants to host it himself. If he does, he can also update the styles to better fit the page the widget resides on.
ExampleComWidget.addListener('update', callback);
Use clever markup
Be sure to use scoping on your classes and ids, to avoid conflicts as much as possible
I.e. if your company's name is example.com, you could use classes like: com-ex-widget-newsItem
<h1>
-tags, since they have especially high ranking in SEO. You could probably get by with using <h4>
and less. This bullet might be a bit off. When in doubt, it's much better to use semantic markup than not.