How to reload a file via require.js triggered from the browsers js console

前端 未结 1 1302
星月不相逢
星月不相逢 2020-12-09 21:09

Having a text file (underscore templates) loaded by require.js on initial app start:

define([\'text!templates/template.html\'], function(Template){ ... };


        
相关标签:
1条回答
  • 2020-12-09 21:18

    RequireJS is not designed for reloading modules, generally speaking.

    However, if you design your application carefully you can get RequireJS to reload some modules. Here's an example:

    <body>
      <p id="contents">Nothing loaded.</p>
      <button id="reload">Reload</button>
      <script>
        require.config({
            baseUrl: "./js",
            paths: {
                jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min',
            }
        });
        require(["jquery"], function ($) {
            var $contents = $("#contents");
            function reload() {
                require.undef("text!../file.html");
                require(["text!../file.html"], function (file) {
                    $contents.empty();
                    $contents.append(file);
                });
            }
            $("#reload").click(reload);
        });
      </script>
    </body>
    

    The key is to call require.undef to undefine the module before reloading it.

    I've got a repo illustrating the whole thing. If you edit the file.html file and hit the "Reload" button, the text of the paragraph will be replaced with the contents of the file. To get a function you can invoke form the console just assign it to a field of window (e.g. window.reload).

    The button should really be called Load/Reload (because it does the initial loading and the reloading) but I'm not going to fix it.

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