Coder Social home page Coder Social logo

example-multipage-shim's Introduction

RequireJS

RequireJS loads plain JavaScript files as well as more defined modules. It is optimized for in-browser use, including in a Web Worker, but it can be used in other JavaScript environments, like Rhino and Node. It implements the Asynchronous Module API.

RequireJS uses plain script tags to load modules/files, so it should allow for easy debugging. It can be used simply to load existing JavaScript files, so you can add it to your existing project without having to re-write your JavaScript files.

RequireJS includes an optimization tool you can run as part of your packaging steps for deploying your code. The optimization tool can combine and minify your JavaScript files to allow for better performance.

If the JavaScript file defines a JavaScript module via define(), then there are other benefits RequireJS can offer: improvements over traditional CommonJS modules and loading multiple versions of a module in a page. RequireJS also has a plugin system that supports features like i18n string bundles, and text file dependencies.

RequireJS does not have any dependencies on a JavaScript framework.

RequireJS works in IE 6+, Firefox 2+, Safari 3.2+, Chrome 3+, and Opera 10+.

Latest Release

License

MIT

Code of Conduct

jQuery Foundation Code of Conduct.

Directories

  • dist: Scripts and assets to generate the requirejs.org docs, and for generating a require.js release.
  • docs: The raw HTML files for the requirejs.org docs. Only includes the body of each page. Files in dist are used to generate a complete HTML page.
  • tests: Tests for require.js.
  • testBaseUrl.js: A file used in the tests inside tests. Purposely placed outside the tests directory for testing paths that go outside a baseUrl.
  • updatesubs.sh: Updates projects that depend on require.js Assumes the projects are siblings to this directory and have specific names. Useful to copy require.js to dependent projects easily while in development.

Tests

This repo assumes some other repos are checked out as siblings to this repo:

git clone https://github.com/requirejs/text.git
git clone https://github.com/requirejs/i18n.git
git clone https://github.com/requirejs/domReady.git
git clone https://github.com/requirejs/requirejs.git

So when the above clones are done, the directory structure should look like:

  • domReady
  • i18n
  • text
  • requirejs (this repo)

You will need to be connected to the internet because the JSONP and remoteUrls tests access the internet to complete their tests.

Serve the directory with these 4 siblings from a web server. It can be a local web server.

Open requirejs/tests/index.html in all the browsers, click the arrow button to run all the tests.

example-multipage-shim's People

Contributors

evverx avatar jrburke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

example-multipage-shim's Issues

Multi-page app + Backbone + Require...is it worth it?

James, apologize in advance...I know this is an "issues" forum, but I have an "issue" as to whether or not it's a smart idea to even try to use RequireJS, Backbone, and a modular dev pattern for multi-page apps. Is it really worth it? Sure seems like a ton of http calls going all over the place, multiple calls for the same resources, diminished pub/sub abilities, etc.

At my company, we have written many apps in the mobile e-commerce space for fortune 500 type companies using the above client side stack, and I absolutely love it...thanks in part to a lot of your work. But recently I had a buddy for a large dev shop ask me to speak to the benefits of using BB in a multi-page environment...and quite frankly, I'm struggling to see why you would use these libs in a multi-page app rather than serve up server side content with the typical jQuery/ajax calls and dom manipulation.

Any thoughts you can share, or good links that speak to these concerns? Sorry again if this is the wrong place to ask this...and thanks again for all your examples and insight :)

example that uses data-main for baseUrl

We are working on a project which serves pages from different urls, for example:

/article
/users/edit

We also want to use cache busting urls, where resources are served with a changing prefix in the path:

/3022123/javascripts/require.js
/3022123/javascripts/common.js

To get require.js to load scripts from correct location, baseUrl can't be relative (HTML page location changes) and because resource url changes baseUrl needs to be defined in a dynamic way.

Here's how we do dynamic and absolute baseUrl using data-main:

<script src="@routes.Assets.at("javascripts/lib/require.js")" data-main="@routes.Assets.at("javascripts/common.js")" type="text/javascript"></script>

@routes.Assets.at("javascripts/common.js") renders a path like /3022123/javascripts/common.js

Unfortunately on some browsers it seems that require.js manages to load other required scripts before common.js has been completed (which results in errors because baseUrl is incorrect), so a trick is needed:

<script type="text/javascript">
        require(["common"], function() {
                require("myApp")
        })
</script>

Are the better ways to do this? The alternative examples under RequireJS API > Configuration Options would work also, but this the most optimized. config in page increases page size and it would make page rendering and js optimization a bit more complex.

It would be nice if there was a more direct way to instruct requirejs that "here's a configuration file, block other loads before continuing". Maybe something like:

<script src="@routes.Assets.at("javascripts/lib/require.js")" requirejs-config="@routes.Assets.at("javascripts/common.js")" type="text/javascript"></script>

Dynamic plugins loading

Hello, we are currently restructuring a large website and this example is definitely what we need. However, we feel the need for an additional entity we called "plugin".

We have pages that are well defined so we know what these pages are going to need and we can create the appropriate mains.js. For example the Homepage, FAQ page and things like that.

Additionaly, we have pages where users can insert plugins themselves. These plugins need specific javascript. For example a form, an interactive agenda, etc... (these are custom plugins, not simple jQuery plugins).
The traditional way to handle that would be to require them all in the appropriate main.js, then do something like:

var pluginFormElements = $('.form-plugin');
if(pluginFormElements.length !== 0){
    requirejs('plugins/form', function(plugin){
        pluginFormElements.each(function(i, elem){
            new plugin({el: elem});
        });
    });
}

The problem is that for each plugin we have to add that snippet and we'd prefer another more dynamic way of doing this.

We think the best solution would be via declarative html so the above snippet can be dynamic and be there only once. Something like this:

<div data-plugin="form"></div>
var pluginElements = $('[data-plugin]');
if(pluginElements.length !== 0){
    pluginElements.each(function(i, elem){
        requirejs('plugins/'+$(this).attr('data-plugin'), function(plugin){
            new plugin(el: elem);
        });
    });
}

Of course, we would require all needed plugins in the appropriate main.js so the optimizer will pack them with main.js and won't make additional HTTP request.

What do you think of this plan ? Would you consider adding this kind of "on demand" capacity to this example ?

Error when compiling with java

Hello,

I'm getting a java.lang.stackoverflowError when compiling with java(supposing the .jar exists in the same directory):

java -classpath js.jar org.mozilla.javascript.tools.shell.Main r.js -o build.js

What I made wrong?
Thanks

Reusing a Require.js shim config between pages

I am interested in creating a single configuration object for all the JavaScript code on my Web site. I found https://github.com/requirejs/example-multipage-shim which is an example of this setup.

From https://github.com/requirejs/example-multipage-shim (emphasis
mine): Since the shim config requires dependencies to be in the page,
instead of using data-main="js/page1" for page1.html, this example
inlines the require calls in the HTML page. If data-main was used
instead, then 'js/page1' could not have any dependencies inlined
,
and instead still rely on the 'common' and 'app/main1' build layers to
hold the modules, due to the restrictions shim config places on the
build.

I do not understand the bolded sentence. Does it mean that "js/page1" if it existed could not declare dependencies? What does it mean to have a dependency inlined? Inlined into what? The HTML file or the JavaScript file?

I read the API doc about shim config, but the limitations that it puts on the optimizer is not clear.

From https://github.com/requirejs/example-multipage-shim/blob/master/www/page1.html:

    <script src="js/lib/require.js"></script>
    <script>
        //Load common code that includes config, then load the app
        //logic for this page. Do the require calls here instead of
        //a separate file so after a build there are only 2 HTTP
        //requests instead of three.
        require(['./js/common'], function (common) {
            //js/common sets the baseUrl to be js/ so
            //can just ask for 'app/main1' here instead
            //of 'js/app/main1'
            require(['app/main1']);
        });
    </script> 

Why is the following wrong? Why does "app/main1" have to be in a separate module from the bootstrap (data-main) code?

    <script src="js/lib/require.js"></script>
    <script>
        require(['js/common'], function (common) {
            var underscore = require('underscore');
            // ...
        });
    </script> 

Clarify common.js as shared.js

This is a really helpful project - thanks for making it available.

Pardon the newb request, but assuming there is no connection between the RequireJS shim config and the CommonJS format, would you consider renaming common.js to shared.js or an alternate synonym?

Any reason not to bundle require.js with common.js?

It would save an extra script load.

There's also a bug (?) where you can't include require if it's named require, you have to alias it first.

{
    appDir: '../www',
    mainConfigFile: '../www/js/common.js',
    dir: '../www-built',
    modules: [
        //First set up the common build layer.
        {
            //module names are relative to baseUrl
            name: '../common',
            //List common dependencies here. Only need to list
            //top level dependencies, "include" will find
            //nested dependencies.
            include: [
                'require',
                'jquery',
                'app/lib',
                'app/controller/Base',
                'app/model/Base'
            ]
        },

        ...

    ]
}

^ doesn't work. You need to do

{
    appDir: '../www',
    mainConfigFile: '../www/js/common.js',
    dir: '../www-built',
    paths: {
        'requirejs': "require",
    },
    modules: [
        //First set up the common build layer.
        {
            //module names are relative to baseUrl
            name: '../common',
            //List common dependencies here. Only need to list
            //top level dependencies, "include" will find
            //nested dependencies.
            include: [
                'requirejs',
                'jquery',
                'app/lib',
                'app/controller/Base',
                'app/model/Base'
            ]
        },
        ...
    ]

Remove page1.js and page2.js in favor of script tags?

I think this is a great example but it feels like a workaround to have to go from page1.html to page1.js to main1.js. I was wondering if it would be better to have a script block on each page after you've loaded require.js that just contains the same code as page1.js and page2.js. You wouldn't be using the data-main attribute so you have to fully specify the path to common.js but if you have a baseUrl in there then everything after that point works the same.

<script src="js/require.js"></script>
<script type="text/javascript">
    // Load common code that includes config,
    // then load the app logic for this page.
    require(['./js/common'], function (common) {
      require(['app/main1']);
    });
</script>

Hopefully I'm not missing some nuance of the load order. If not then I think this is a nicer approach as it cuts down on an HTTP request to page1.js and it's a bit easier to sell to skeptical team members.

enforceDefine = true causes issues

Hi there,

We have been trying to sort out getting requirejs going in our project, and are almost there (I think). Out last issue is getting enforceDefine working. We have a setup similar in style to this little project. When we set enforceDefine: true in our config, we get 'No define call for ...' errors.

Trying out this little project on my machine, I get exactly the same error if I turn enforceDefine on. What changes are needed to make it work for this project? Then I can go and see if I can make it work for our project.

Thanks,
Dylan

Optimisation

I've been following the pattern this repo illustrates, and it is beautiful until I run r.js.

Would an example r.js configuration be out of scope?

I'd be happy to provide my own config, but since it's producing 'mismatched' errors, it's not much use yet....

require&requirejs

lib = require('./lib'),
change to
lib = requirejs('./lib'),
open page1.html, but it reported an error
Uncaught Error: Module name "lib" has not been loaded yet for context: _. Use require([])
why?

Issue with Shim not always loading dependencies

Hello, I'm having an issue where dependencies defined within shim don't always load before other modules that depend on them load.

There are a few behaviors leading me to this conclusion:

  • I've noticed this behavior happens sporadically... sometimes everything loads in order... it's only approx 1 in 6 page refreshes (And cache clears) that I notice this problem. This leads me to believe that sometimes the scripts load quickly enough to be executed in order, hence no issues.
  • Adding a define() to the plugin, and removing all shim code solves the problem 100%
  • When there happens to be an error from a dependency not loading, after a second ro two the scripts work fine... suggesting the script has finally loaded.

Here is a sample of the code I'm using:

common.js

shim: {
    'bootstrap': {
        deps: ['jquery'] 
    },
    'icanhaz': {
        deps: ['jquery']  
    },
    'imagesloaded': {
        deps: ['jquery']
    },
    'imageload': { 
        deps: ['jquery', 'imagesloaded']
    },
    'lazyload': {
        deps: ['jquery', 'imagesloaded', 'imageload']
    }
}

html file:

<script src="<?=site_url('assets/js/plugins-vendor/require-jquery.js');?>"></script>
<script>
require(['assets/js/common'], function (common) {
    require(['lazyload', 'public/photo_album']);
});
</script>

public/photo_album.js

$(function () {

console.log('Photo gallery code loaded');

// get our products
$.getJSON(CI.site_url + 'gallery/get_gallery').done(callbackProducts)

// callback on products get
function callbackProducts(rsp) {

    // create gallery
    var gallery_items = ich.gallery(rsp)

    // append products to gallery area
    $('#photos').append(gallery_items)

    // lazy load plugin, loads only image in view
    $('.photo-album > img').lazyload();

    // forces scroll of 0 pixels to make sure first slide loads
    $(document).trigger('scroll');
}

});

The issue is that $.lazyload() requires $.imageload() as a dependency but it's not being loaded in time. The error I get is from the lazyload script, that imageload() is not defined. However, if I wait a split second the plugin works as expected, regardless of the error.

@note that I have tried removing 'lazyload' from the shim, but this still fails. The only fix is to remove all shims and add a define(['imageload']) to the .lazyload plugin... but this is what shim is suppose to help with!

Thanks in advance for your help!
-Matt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.