I'm using in my project require.js and it's plugin use.js.
require.config({
// Initialize the application with the main application file
deps: ["main"],
paths: {
// JavaScript folders
libs: "../assets/js/libs",
plugins: "../assets/js/plugins",
// Libraries
jquery: "../assets/js/libs/jquery",
underscore: "../assets/js/libs/underscore",
backbone: "../assets/js/libs/backbone",
jqueryUI: "../assets/js/libs/jqueryUI",
jquerySlider: "../assets/js/libs/slider",
jqueryMouseWheel: "../assets/js/libs/jquery.mousewheel",
jquerySelectBox: "../assets/js/libs/selectBox",
jqueryMouse: "../assets/js/libs/mouse",
bookReader: "../assets/js/libs/newReader",
// Shim Plugin
use: "../assets/js/plugins/use"
},
use: {
backbone: {
deps: ["use!underscore", "jquery"],
attach: "Backbone"
},
underscore: {
attach: "_"
},
jqueryUI: {
deps: ["jquery"]
},
jquerySlider: {
deps: ["jquery", "jqueryMouse"]
},
jquerySelectBox: {
deps: ["jquery"]
},
jqueryMouse: {
deps: ["jquery", "jqueryUI"]
},
jqueryMouseWheel: {
deps: ["jquery", "jqueryUI"]
},
bookReader: {
deps: ["jquery", "jqueryUI", "jqueryMouse", "jquerySlider", "jqueryMouseWheel", "jquerySelectBox"],
attach: "Reader"
}
}
});
The problem is that scripts start load simultaneously, and because of that there are unmet dependencies, often there are these two errors
Uncaught TypeError: Object function (a, b) {return new e.fn.init (a, b, h)} has no method 'widget': 4444/assets/js/libs/mouse.js: 15
Uncaught TypeError: Cannot read property 'mouse' of undefined: 4444/assets/js/libs/slider.js: 20
Once the files are in the cache, the problem no longer occurs.
So, my question. How do I specify that the script must loaded consistently?
It is possible to build scripts that wrap them into one file. But this option is not very desirable
Thank you!
Have a look at this AMD loader plugin called STEP, it allows you to load scripts in sequential order.
https://github.com/requirejs/step
Related
I have read the answer to this question require js loading scripts from cdn fail. But in my case it does not help. I have a require JS setup and I want to use CDN to load my libraries.
The Require JS documentation says below is the right way to load libs from CDN with a fallback to local files.
requirejs.config({
//To get timely, correct error triggers in IE, force a define/shim exports check.
enforceDefine: true,
paths: {
jquery: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min',
//If the CDN location fails, load from this location
'lib/jquery'
]
}
});
require(['jquery'], function ($) {
});
I am using the same method but I get an error instead, below is my code
requirejs.config({
baseUrl: location.protocol + '//' + location.host + '/app',
waitSeconds: 0,
paths: {
'jquery': ['https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min','/assets/js/vendor/jquery'],
'jqueryPjax': '/assets/js/vendor/jquery.pjax',
'jqueryUI': '/assets/js/vendor/jquery-ui.min',
'jqueryMousewheel': '/assets/js/jquery.mousewheel',
'jScrollPane': '/assets/js/jquery.jscrollpane.min',
'fastclick': '/assets/js/vendor/fastclick',
'jquerySlidebars': '/assets/js/jquery.slidebars.min',
'imagesLoaded': '/assets/js/imagesloaded.pkgd.min',
'fancyBox': '/assets/js/jquery.fancybox.pack',
'fancyBoxThumb': '/assets/js/jquery.fancybox-thumbs',
'text': '/assets/js/vendor/text',
'chosen': '/assets/js/vendor/chosen',
'bb': '/assets/js/vendor/backbone-min',
'underscore': '/assets/js/vendor/underscore-min',
'angular': '/assets/js/angular.min',
'ventFactory': 'base/ventFactory',
'util': 'base/util',
'dom': 'base/dom',
'actionHandler': 'base/actionHandler',
'ajax': 'base/ajax'
},
shim: {
'jquery': {
exports: 'jQuery'
},
'jqueryUI': {
deps: ['jquery']
},
'angular': {
exports: 'angular'
},
'jqueryPjax': {
deps: ['jquery'],
exports: 'jQuery.fn.pjax'
},
'jqueryMousewheel': {
deps: ['jquery'],
exports: 'jQuery.fn.mousewheel'
},
'jScrollPane': {
deps: ['jqueryMousewheel'],
exports: 'jQuery.fn.jScrollPane'
},
'jquerySlidebars': {
deps: ['jquery'],
exports: 'jquerySlidebars'
},
'fancyBox': {
deps: ['jquery'],
exports: 'fancyBox'
},
'fancyBoxThumb': {
deps: ['jquery', 'fancyBox'],
exports: 'fancyBoxThumb'
},
'chosen': {
deps: ['jquery'],
exports: 'chosen'
}
}
});
requirejs(['jquery', 'app'], function($, app) {
$(function() {
app.start();
});
});
I have just made the changes for Jquery as of now and I am giving both CDN URL and local path but when I load my page I get an error
TypeError: $el.siblings is not a function
Adding on
I am using Require JS for loading my libs but then at the production I am using almond, which combines all modules into one single file, so has this something to do with the error ?
Any help on this is highly appreciated. Thanks
Adding on I am using Require JS for loading my libs but then at the production I am using almond, which combines all modules into one single file, so has this something to do with the error ?
Yes, it does. Almond cannot do dynamic loading. In other words, everything you want Almond to load must be into a single bundle of modules. You cannot use a CDN with Almond.
"No dynamic loading" is the first restriction in its list of restrictions.
OK, so my problem is that I'd like to be able to automatically delete parts of the shim config I've set up for RequireJS; rather than loading the entire minified Bootstrap file I split it up into the different plugins, so that I get the benefit of less filesize when my application uses less of the Bootstrap components. E.g:
require.config({
paths : {
jquery : 'vendor/jquery/jquery.min',
bootstrap : 'vendor/bootstrap-sass/js'
},
shim : {
'bootstrap/affix': { deps: ['jquery'], exports: '$.fn.affix' },
'bootstrap/alert': { deps: ['jquery'], exports: '$.fn.alert' },
'bootstrap/button': { deps: ['jquery'], exports: '$.fn.button' },
'bootstrap/carousel': { deps: ['jquery'], exports: '$.fn.carousel' },
'bootstrap/collapse': { deps: ['jquery'], exports: '$.fn.collapse' },
'bootstrap/dropdown': { deps: ['jquery'], exports: '$.fn.dropdown' },
'bootstrap/modal': { deps: ['jquery'], exports: '$.fn.modal' },
'bootstrap/popover': { deps: ['jquery'], exports: '$.fn.popover' },
'bootstrap/scrollspy': { deps: ['jquery'], exports: '$.fn.scrollspy' },
'bootstrap/tab': { deps: ['jquery'], exports: '$.fn.tab' },
'bootstrap/tooltip': { deps: ['jquery'], exports: '$.fn.tooltip' },
'bootstrap/transition': { deps: ['jquery'], exports: '$.support.transition' },
}
});
Whilst the r.js optimizer correctly identifies that I'm only using bootstrap/dropdown, it still includes the shim config for files that don't end up in the production code. So my question is can I get rid of the unused shim files automatically? I'm using grunt-contrib-requirejs for the actual optimization and have had no problems with that. A Grunt based solution would be preferable but I'm open to anything else. Thanks.
To summarize the great points made above, and hopefully close the question
Unused shim configs are not removed by r.js since it can't know if you need them at run-time
~175 bytes (gzipped) are not worth manually optimizing, especially as part of a payload 200 times that big, and won't cause noticeable improvement
AMDClean could be an automated way to de-AMDify your scripts completely and thus meet your size-saving desires
I can't seem to figure out how to load Bootstrap via RequireJS. None of the examples that I found worked for me.
Here is my shim:
require.config({
// Sets the js folder as the base directory for all future relative paths
baseUrl: "./js",
urlArgs: "bust=" + (new Date()).getTime(),
waitSeconds: 200,
// 3rd party script alias names (Easier to type "jquery" than "libss/jquery, etc")
// probably a good idea to keep version numbers in the file names for updates checking
paths: {
// Core libsraries
// --------------
"jquery": "libs/jquery",
"underscore": "libs/lodash",
"backbone": "libs/backbone",
"marionette": "libs/backbone.marionette",
// Plugins
// -------
"bootstrap": "libs/plugins/bootstrap",
"text": "libs/plugins/text",
"responsiveSlides": "libs/plugins/responsiveslides.min",
'googlemaps': 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDdqRFLz6trV6FkyjTuEm2k-Q2-MjZOByM&sensor=false',
// Application Folders
// -------------------
"collections": "app/collections",
"models": "app/models",
"routers": "app/routers",
"templates": "app/templates",
"views": "app/views",
"layouts": "app/layouts",
"configs": "app/config"
},
// Sets the configuration for your third party scripts that are not AMD compatible
shim: {
"responsiveSlides": ["jquery"],
"bootstrap": ["jquery"],
"backbone": {
// Depends on underscore/lodash and jQuery
"deps": ["underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Backbone"
},
"marionette": {
// Depends on underscore/lodash and jQuery
"deps": ["backbone", "underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Marionette"
},
'googlemaps': { 'exports': 'GoogleMaps' },
// Backbone.validateAll plugin that depends on Backbone
"backbone.validate": ["backbone"]
},
enforceDefine: true
});
and here is how I call Bootstrap:
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
'bootstrap',
],
function($, _, Backbone, Marionette, Navigations, Bootstrap){
The error that I get is this:
Uncaught Error: No define call for bootstrap
Any ideas on how to get this resolved?
I found a working example here:
https://github.com/sudo-cm/requirejs-bootstrap-demo
I followed it to get my code to work.
According to that demo, especially app.js, you simply make a shim to catch Bootstrap's dependency on jQuery,
requirejs.config({
// pathsオプションの設定。"module/name": "path"を指定します。拡張子(.js)は指定しません。
paths: {
"jquery": "lib/jquery-1.8.3.min",
"jquery.bootstrap": "lib/bootstrap.min"
},
// shimオプションの設定。モジュール間の依存関係を定義します。
shim: {
"jquery.bootstrap": {
// jQueryに依存するのでpathsで設定した"module/name"を指定します。
deps: ["jquery"]
}
}
});
and then mark Bootstrap as a dependency of the app itself, so that it loads before app.js.
// require(["module/name", ...], function(params){ ... });
require(["jquery", "jquery.bootstrap"], function ($) {
$('#myModalButton').show();
});
Finally, since app.js is the data-main,
<script type="text/javascript" src="./assets/js/require.min.js" data-main="./assets/js/app.js"></script>
Bootstrap's JS is guaranteed to load before any application code.
Bootstrap lib does not return any object like jQuery, Underscore or Backbone: this script just modifies the jQuery object with the addition of new methods. So, if you want to use the Bootstrap library, you just have to add in the modules and use the jquery method as usual (without declarating Bootstrap like param, because the value is undefined):
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
"bootstrap",
],
function($,_,Backbone,Marionette,Navigations){
$("#blabla").modal("show"); //Show a modal using Bootstrap, for instance
});
I found it was sufficient to add the following to my requirejs.config call (pseudocode):
requirejs.config({
...
shim: {
'bootstrap': {
deps: ['jquery']
}
}
});
I like to use Require.Js ORDER plugin, what it does? Simply loads all your Libraries in order, in this case you won't get any errors, ohh and bootstrap depends on jQuery, so we need to use shim in this case:
requirejs.config({
baseUrl: "./assets",
paths: {
order: '//requirejs.org/docs/release/1.0.5/minified/order',
jquery: 'http://code.jquery.com/jquery-2.1.0.min',
bootstrap: '//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min'
},
shim: {
'bootstrap': {
deps:['jquery']
}
}
});
require(['order!jquery', 'order!bootstrap'], function($) {
});
I am having difficulty trying to get signalr to work with requirejs. This is my code I have but I get the following error:
_Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/hubs'></script>._
Code:
<script src="~/Scripts/jquery.signalR-1.0.0-rc2.js"></script>
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
// requirejs configuration setup
requirejs.config({
baseUrl: '#string.Format("{0}://{1}{2}Scripts/modules", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))', // this might need to change as it depends on the number of / in the url...?
paths: {
'jquery': '../jquery-1.9.0',
'bootstrap': '../bootstrap',
'knockout': '../knockout-2.2.1',
'noext': '../noext',
'sigr': '../jquery.signalR-1.0.0-rc2'
},
shim: {
"sigr": {
deps: ['jquery']
},
"noext!signalr/hubs": {
deps: ['sigr']
}
}
});
Does anyone have any ideas as to why or how I can get this to work?
I was able to get require to work with requirejs..I followed the tutorial on http://requirejs.org/docs/jquery.html on how to plugin jquery and added signal references for this to work
require(["jquery", "jquery.alpha", "jquery.beta","jquery.signalr-1.0.0-rc2","/signalr/hubs"],
function($) {
}
);
I think you have to modify your configuration to do either of the following
Option1:
paths: {
'jquery': '../jquery-1.9.0',
'bootstrap': '../bootstrap',
'knockout': '../knockout-2.2.1',
'noext': '../noext',
'sigr': '../jquery.signalR-1.0.0-rc2'
'hubs': '/signalr/hubs'
},
Option2:
shim: {
"sigr": {
deps: ['jquery']
},
"noext!**/**signalr/hubs": {
deps: ['sigr']
}
}
I'm having some strange issues with our application not executing javascript
I have a web view thats loaded in an iPad app.
the page renders using require and backbone but something prevents the external libraries to execute.
the issues are with both d3.js and a jquery countdown plugin.
using firebug I dont get any errors but the countdown isnt starting.
same with d3 drawing some things but click functionality isnt working
im not sure if its a require issue or an iOS6 issue.
if it was a require issue i assume we'd get errors. but we dont.
anyone have any clues to what might be the issue?
main controller looks like this
/*global require: false */
/*jslint nomen: true */
// Sets up common libraries for all pages
require.config({
paths: {
// Major libraries
'jquery': 'lib/jquery-1.8.2.min',
//'jquery.mobile': 'lib/jquery.mobile-1.2.0.min',
//'jquery.mobile-config': 'lib/jquery.mobile-config',
'underscore': 'lib/underscore-min',
'backbone': 'lib/backbone-min',
'fastclick': 'lib/fastclick.min',
'easing': 'lib/jquery.easing.1.3',
'countdown':'lib/jquery.countdown.min',
// Require.js plugins
'text': 'lib/text',
'socket.io': 'lib/socket.io.min'
},
shim: {
'jquery': {
exports: '$',
exports: 'jQuery'
},
'easing': ['jquery'],
//'jquery.mobile-config': ['jquery'],
//'jquery.mobile': ['jquery','jquery.mobile-config'],
'fastclick': {
exports: 'FastClick'
},
'countdown': {
deps: ['jquery'],
exports: 'countdown'
},
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'socket.io': {
exports: 'io'
}
}
});
require(['jquery', 'underscore', 'views/main-view', 'view-controller','fastclick', 'easing', 'countdown'], function ($, _, MainView, ViewController, fc, easing, countdown) {
"use strict";
var mainView = new MainView();
$("body").html(mainView.render().el);
ViewController.initialize();
});