Can you make a javascript function replace itself on the page with custom html?

后端 未结 4 1351
无人及你
无人及你 2021-01-13 18:42

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

相关标签:
4条回答
  • 2021-01-13 18:58

    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!

    0 讨论(0)
  • 2021-01-13 19:04

    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.

    0 讨论(0)
  • 2021-01-13 19:17

    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>
    
    0 讨论(0)
  • 2021-01-13 19:18

    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.

    0 讨论(0)
提交回复
热议问题