0

I'd like to create a web page plugin (not a jQuery plugin) that can be installed by the webmaster by pasting a few lines of code into their HTML.

For example:

<script src=".../plugin.js" />
<script>window.plugin(parent_element, {some: "config"});</script>

Disqus does this:

<div id="disqus_thread"></div>
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
    var disqus_shortname = 'asdasdsadad'; // required: replace example with your forum shortname

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

(I'm not sure why Disqus needs to run Javascript to add Javascript to the header.)

The plugin will create a new html element and require css for that element.

I'm using http://youmightnotneedjquery.com/ to avoid dependency on jQuery.

I'm only targeting IE9+, FF and Chrome.

What is common practise for loading css from a <script> tag?

(I really want the webmaster to be able to override the plugin's css, to style it.)

What is the best way to produce the html? Elements, raw strings, functions or some form of templating library?

fadedbee
  • 42,671
  • 44
  • 178
  • 308

1 Answers1

1

The most probable reason a plugin creator would want to add the js to the head from within the body is to ensure that anyone (even those who don't necessarily have access to the head) can use the plugin.

If you wanted to override the existing CSS directives, all you need to do is to ensure yours comes last. Considering you're overriding, sometimes you may have to use !important but that really depends on the specific elements' so called specificity. You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

EDIT: as pointed out by @Yousef_Shamshoum in the comment to the original question, here is an SO question that answers the how to on adding CSS files using JavaScript (ie. "loading css from a <script> tag"): How to load up CSS files using Javascript?

Community
  • 1
  • 1
benomatis
  • 5,536
  • 7
  • 36
  • 59