How to tell requirejs to load only the javascript required by the current page

I'm using requirejs in a wordpress plugin. I'm trying to use it so that only the javascript needed for the page is loaded. My idea is to have a main.js file that loads the js for the current page, but i was wondering how to tell main.js what file to load.

require( 
    [ "pages/name-of-the-page" ], // How do i tell require that we are on page x?
    function( page ) { 
        page.start();
    }
);

I was thinking about what to use, maybe i should set a cookie server-side, read it and then use that data?Use the url parameters to guess the page?What should i do?

Answers


It would seem more sensible to just load core JS modules in your main.js (since it will be loaded on every page) and then for each page require only the code you need.

One crude way is to check in wordpress what page is currently loaded and then load your files there:

<?php if (is_page('Contact')): ?>
<script>
    require(['scripts/pages/contact.js']);
    // Note use of a plain js file, and not a module
</script>
<?php endif; ?>

Then in contact.js

require(['some/contact/module'], function(contact) {
    // do cool stuff
});

I covered a similar situation in this answer that may help as well.


Need Your Help

How can I draw the control points of a Bézier Path in Java?

java drawing vector-graphics bezier java-2d

I have created a Path of Bézier curves and it works fine to draw the path. But I don't know How I can draw the Control Points together with the Path. Is that possible or do I have to keep track of ...

javascript if else statement error

javascript

I am trying to check if the name text field is empty. if it is, then i want to show a div that says "please enter your name". i do a test, and name='name'. but after that, nothing else pops up....