Search code examples
javascriptevalblockly

Is it possibly to re-load a JS script file dynamically?


We're looking at using Blockly to enable power-users to design business rules in a non-coding, sandboxed way.

When they edit their diagram to regenerate new JS code, I would like to reload this into the browser. One aspect of this is, if the code is saved as an external JS script, how can I reload it in the browser without refreshing the whole page?


Solution

  • Even though your explanation is extremely messy, I’ll try to stick to the title and provide an example of how you might re-load a specific JS file dynamically (apologies if it is not what you were looking for, but then you’d better re-write your question).

    I guess you did not search Google a lot, because in this SO answer you find how to re-load a JS file:

    function reloadJs(src) {
        src = $('script[src$="' + src + '"]').attr("src");
        $('script[src$="' + src + '"]').remove();
        $('<script/>').attr('src', src).appendTo('body');
    }
    

    As the user points out, you can remove the old tag, but for that the code runtime should already be done. You just need to call the function specifying the source’s address.

    That will literally reload the file, but you want to pass some modifications, therefore you need to run on server-side a script that serves the files according to your needs. You can specify information as GET parameters in your JS reload, such as ‘?parameter1=data1&parameter2=data2’.

    However, I do not recommend to do that, form me the JS code should instead make AJAX calls to modify its behaviour, and not reload the entire file. But that is up to you.

    Edit

    If I understand you correctly, what you want to do actually is to give the client the actual JS code, and not to run the file in the server, according to some diagrams they design which will eventually build into JS code. Then what you could to is to have a <div> tag with a <pre><code> tags inside whose content is changed with jQuery through an AJAX call.

    Then you should not actually load the JS file as a script, since that will make the browser execute it. What you have to do is something like this:

    index.html

    <div>
        <pre>
            <code id=“myCode”>
                Your JS file will show soon.
            </code>
        </pre>
    </div>
    

    As from jQuery documentation:

    script.js

    var jqxhr = $.get( "myFile.js", function(data) {
      $(“#myCode”).html(data)
    })
      .done(function() {
        alert( "second success" );
      })
      .fail(function() {
        alert( "error" );
      })
      .always(function() {
        alert( "finished" );
      });
    

    You obviously have to reference the JS file in your HTML file or it won’t load. You can encapsulate that inside a function and call it according to your convenience.