Example:
mysite.com/page1
depends on scripts in module1.js
mysite.com/page2
depends on scripts in module2.js
mysite.com/page3
depends on scripts in module3.js
Does anyone have any best practices for only running the Javascript required for that specific page. Before I started using RequireJS I would use only one Javascript file and init only the modules I needed for that page. like this
In page <head>
:
var page = "pageTitle";
In Main JS File:
var myModules = {};
myModules.pageTitle = (function(){
return {
init: function(){
alert('this module has been initiated');
}
}
})();
myModules[page].init();
Not really sure sure how a technique like this would work with RequireJS. Would love some feedback and advice on how others are doing this.
RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.
The main difference between AMD and CommonJS lies in its support for asynchronous module loading. "The main difference between AMD and CommonJS lies in its support for asynchronous module loading."
So, RequireJS doesn't support it. From your use case it seems that you don't need synchronous RequireJS, you need to return result asynchronously. AMD pattern allows to define dependencies and load them asynchronously, but module's factory function must return result synchronously.
shim: Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value. Here is an example. It requires RequireJS 2.1. 0+, and assumes backbone. js, underscore.
I assume you have one main.js file for all your pages?
Anyway, typically you would use the data-main attribute of the script tag as explained in the API documentation, which would mean you have one main js file per page. This way, you can get rid of the literal javascript code in you page, and take full advantage of the RequireJS optimization step.
Example:
Develop you main.js file as a RequireJS module:
define([<dependencies go here>], function(){
return function(pageTitle){
//do you page dependent logic here
}
}
In your html, you'll have something like:
<html>
<head>
<script src="require.js"></script>
<script>
require(["main.js"], function(init){
init("pageTitle");
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With