I have some javascript which will create some sort of widget on a page. I will be giving this snippet to clients so I want them to have to do very little.
The most o
So you want to have a script element which replaces itself with div.
Your initial code is like this:
<div id="divContent"></div>
<script>
MakeWidget('divContent');
</script>
You can rewrite it like this (I am using JQuery):
<script id="scriptContent">
$('#scriptContent').after('<div id="divContent"></div>');
MakeWidget('divContent');
$('#scriptContent').remove();
</script>
I have not tried it though!
You have to have MakeWidget
defined somewhere, right? Presumably this is going to be in an external script. Why not just have the external script source just attach itself to the divContent
using the window.onload
method?
This would result in this code on your client's page:
<script src="http://foo.com/makewidget.js"></script>
Your makewidget.js
code could then look like this:
window.onload = function() { MakeWidget('divContent') }
There may some issues with other scripts loading and probably some cross-browser compatibility issues but that should get you pointed in the right direction.
Can you replace a Script Tag with a Div using Javascript in that Script Tag?
Yes. When the <script>
element is reached, assuming it is not a defer
or async
script, it will be the last script element in the page so far. So you can say, either inline or in an external script:
<script type="text/javascript">
(function() {
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
var div= document.createElement('div');
div.innerHTML= 'Whatever content is going to be inserted';
script.parentNode.insertBefore(div, script);
})();
</script>
I would think it would be possible to do it as follows:
<div id="divWidgets">
<script type="text/javascript">
MakeWidgets("divWidgets");
</script>
</div>
The end result should be (if I understand your description correctly) that MakeWidgets will replace the contents of the DIV, which, in this case, is the script itself.