1

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?

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • I don't understand why requirejs would need the name of he page you are on. require is concerned with Javascript mpdules, not with HTML pages... – hugomg Jun 06 '12 at 18:11
  • @missingno that's because if i'm on page 'a' i want only to load the javascript for page 'a', while on page 'b' i only want to load javascript for page 'b' – Nicola Peluchetti Jun 06 '12 at 19:10

1 Answers1

1

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.

Community
  • 1
  • 1
Simon Smith
  • 8,024
  • 2
  • 30
  • 40