Loading module once, requirejs with examples

前端 未结 1 847
醉梦人生
醉梦人生 2021-02-09 19:00

I already ask similar question: Requirejs, what it means "Requirejs loads each module once"
but in that topic no one answer the main question, because i asked in

相关标签:
1条回答
  • 2021-02-09 19:15

    I changed your main.js to log to the console

    require(['test1', 'test2', 'counter'], function(test1, test2, counter) {
            console.log("Executing main");
            console.log(counter.get());
    });
    

    In addition I have an index.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>My Counter Demo</title>
        <link rel="stylesheet" type="text/css" href="css/main.css">
        <script data-main="scripts/main" src="scripts/require.js"></script>
    </head>
    <body>
        <h1>My Counter Demo</h1>
    </body>
    </html>
    

    After loading index.html and then opening the web console I have

    [22:04:09.077] "Executing counter"
    [22:04:09.077] "Executing test1"
    [22:04:09.077] "Executing test2"
    [22:04:09.077] "Executing main"
    [22:04:09.078] 2 
    

    Log messages

    To make it more clear what happens I suggest to substitute the log messages

    • Executing counter -> Creating the counter AMD module
    • Executing test1 -> Incrementing the counter in module "test1"
    • Executing test2 -> Incrementing the counter in module "test2"
    • "Executing main" -> Retrieving the counter value in module "main"

    The I get the following result in the console log

    [22:16:46.368] file:///C:/Users/User/Documents/requirejs-counter2/css/main.css
    [22:16:46.368] file:///C:/Users/User/Documents/requirejs-counter2/scripts/require.js
    [22:16:46.369] file:///C:/Users/User/Documents/requirejs-counter2/scripts/main.js
    [22:16:46.588] file:///C:/Users/User/Documents/requirejs-counter2/scripts/test1.js
    [22:16:46.589] file:///C:/Users/User/Documents/requirejs-counter2/scripts/test2.js
    [22:16:46.590] file:///C:/Users/User/Documents/requirejs-counter2/scripts/counter.js
    [22:16:46.381] "Creating the counter AMD module"
    [22:16:46.381] "Incrementing the counter in module "test1""
    [22:16:46.381] "Incrementing the counter in module "test2""
    [22:16:46.381] "Retrieving the counter value in module "main""
    [22:16:46.381] 2
    

    Conclusion

    The counter module is only loaded once and thus creating the counter object only once. You may consider it to be a Singleton.

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