Am using requiredjs. After deployment to the any environment (now screenshot from local) am getting refresh issue. page is not loading properly. I have checked in network tab in firebug. its showing(below image). when the file get 200 OK (BF Cache) status, page not loading properly.
Error:
After giving ctrl+f5
all the pages are coming correctly.
some time i need to give lot of ctrl+f5 then only its working asexpected
my requirejs config file:
require.config({
baseUrl: "../../../../../../../Scripts",
//waitSecond: 0,
//urlArgs : "q="+new Date().getTime(),
enforcedefine: true,
paths: {
//RequireJS Plugins.
'text': 'lib/requirejs/text',
'domReady': 'lib/requirejs/domReady',
'app': 'app',
'noext': 'lib/requirejs/noext',
// Shared Libraries.
'jquery': 'lib/Kendo/jquery.min',
'jqueryMigrate': 'lib/jquery-migrate-1.2.1.min',
'jszip': 'lib/jszip',
'kendo': 'lib/Kendo/kendo.all.min',
'materialize': 'lib/materialize/materialize',
'jqueryValidate': 'jquery.validate.min',
'jsignature': 'lib/jSignature/jSignature.min',
'jqueryMaskedinput': 'lib/jquery/jquery.maskedinput.min',
'jqueryMd5': 'lib/jquery/jquery.md5',
'truckNotifier': 'Controls/serviceTruck.Notifier'
},
shim: {
'app': {
deps: ['kendo']
},
'kendo': {
deps: ['jquery', 'jszip'],
},
'jqueryExtensions': {
deps: ['jquery'],
},
'materialize': {
deps: ['jquery', 'kendo'],
},
'krossRespJs': {
deps: ['jquery'],
},
'jqueryMaskedinput': {
deps: ['jquery'],
},
'truckUploadSelector': {
deps: ['jquery'],
},
'underscore': {
exports: '_'
}
}
});
app.js file:
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([
'domReady!',
'text',
'noext',
'jquery',
'kendo',
'jszip',
'truckNotifier'
], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function (domReady,text,noext,$,kendo,jszip,truckNotifier) {
'use strict';
var app = kendo.observable({
// ---- PUBLIC FIELDS ----
DATE_FORMAT: 'MM/dd/yyyy',
DATE_MASK: '99/99/9999',
DATE_TIME_FORMAT: 'MM/dd/yyyy HH:mm',
DATE_TIME_MASK: '99/99/9999 99:99',
PHONE_MASK: '(999) 999-9999',
TIME_FORMAT: 'HH:mm',
TIME_MASK: '99:99',
$notifier: $('#notify_container'),
router: new kendo.Router(),
isInitialized: false,
/** This call sets up background components of the current page. */
initialize: function () {
var self = this;
// Initialize this first so it can show loading while the rest
// of this module loads.
if (!self.isInitialized) {
$('.link-external').attr('target', '_blank');
$('#notify_container').serviceTruckNotifier();
self.isInitialized = true;
}
window.JSZip = jszip;
},
showPleaseWait: function (show) {
},
/* Pops up a notification at the top of the page. */
notify: function (type, message) {
var types = {
'push': 'notifyPush',
'info': 'notifyInfo',
'success': 'notifySuccess',
'error': 'notifyError',
'warn': 'notifyWarn',
'expired': 'notifyExpired'
};
this.$notifier.serviceTruckNotifier(types[type], message);
}
});
app.initialize();
return app;
}));
script used in View Page:
<script>
require([
'domReady!',
'text',
'noext',
'app',
'jquery',
'jqueryValidate',
'kendo',
'truckNotifier'
],
function (
domReady,
text,
noext,
app,
$,
jqueryValidate,
kendo,
truckNotifier
) {
var notifier = $('#notify_container'),
message = '#(ViewBag.Message)';
$("#primaryTextButton").kendoButton();
$('.all-content').removeClass('dn');
$('.mcenter').addClass('dn');
if (message != "") {
notifier.serviceTruckNotifier("notifyExpired", "#C.LINK_HAS_BEEN_EXPIRED");
}
});
</script>
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/Styles/all/css")
<script src="~/Scripts/lib/requirejs/require.js"></script>
<script src="~/Scripts/config.js"></script>
</head>
<body id="#RenderSection("BodyId", false)">
#{
System.Reflection.Assembly web = typeof(ServiceTruck.Web.Models.ExternalLogin).Assembly;
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(web.Location);
string version = fvi.FileVersion;
System.Reflection.AssemblyName webName = web.GetName();
string myVersion = version.ToString();
ViewBag.Version = myVersion;
}
#RenderSection("featured", required: false)
<section class="container-fluid">
#RenderBody()
</section>
<!-- Service Truck Layout Footer Start -->
<footer class="copy-right">
<div class="col-md-6 text-left">
<p>All rights reserved.</p>
<p>Copyright © 2016 Name.</p>
</div>
<div class="col-md-6 text-right">
<p>Build #myVersion</p>
<p>Recommended Browsers: Internet Explorer 11, Firefox 48, Chrome 52</p>
</div>
</footer>
<!-- Service Truck Layout Footer End -->
#RenderSection("scripts", required: false)
</body>
</html>
One thing that is definitely wrong with your configuration is the shim for app:
'app': {
deps: ['kendo']
},
Your app module is an AMD module: it calls define. So you cannot use a shim for it. Setting a shim for a module that cannot benefit from one can lead to undefined behavior.
I've run experiments with this at times and got inconsistent results from one version of RequireJS to the next. The point is that setting a shim for an AMD module has no defined semantics.
Related
I am trying to build my project as a Self-Executing Bundle (SFX) with Gulp and SystemJS-Builder. When I run my gulp task, I keep getting the error, "window is not defined." I researched the issue and could not find a solution.
Here is my gulp build file
var gulp = require('gulp');
var path = require('path');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var Builder = require('systemjs-builder');
gulp.task('bundle:js', function () {
var builder = new Builder('MyApplication/application/source', 'MyApplication/application/source/config.js');
return builder.buildStatic('MyApplication/application/source/app.js', 'MyApplication/application/js/Site.min.js', {
format: "amd"
});
});
Here is my SystemJS configuration:
(function () {
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
var kendoVersion = "2016.3.914";
var map = {
text: "../Scripts/text.js",
app: "app.js",
main: "main.js",
aes: "../../../Scripts/aes.js",
jquery: "../../../Scripts/kendo/" + kendoVersion + "/jquery.min.js",
kendo: "vendor/kendo/kendo.js",
DataTables: "../../../Scripts/DataTables/datatables.js",
k: "../../../Scripts/kendo/" + kendoVersion + "/",
bootstrap: "../../../Scripts/bootstrap.js",
lodash: "../../../Scripts/lodash.js",
moment: "../../../Scripts/moment.js",
ajaxSetup: "security/ajaxSetup.js",
q: "../../../Scripts/q.js",
toastr: "../../../Scripts/toastr.js",
wizards: "viewmodels/shared",
'kendo.core.min': "../../../Scripts/kendo/" + kendoVersion + "/kendo.core.min.js"
};
var paths = {
'kendo.*': "../../../Scripts/kendo/" + kendoVersion + "/kendo.*.js",
jquery: "../../../Scripts/kendo/" + kendoVersion + "/jquery.min.js",
bootstrap: "../../../Scripts/bootstrap.js"
};
var meta = {
app: { deps: ["kendo", "jquery"] },
main: { deps: ["jquery"] },
jquery: { exports: ["jQuery", "$"], format: "global" },
kendo: { deps: ["jquery"] },
bootstrap: { deps: ["jquery"] },
'kendo.core.min': { deps: ["jquery"] },
DataTables: { deps: ["jquery"], exports: "$.fn.DataTable" },
toastr: { deps: ["jquery"] }
};
var packages = {
pages: {
main: 'views/*.html',
format: 'amd',
defaultExtension: 'html'
}
};
var config = {
baseURL: "application/source",
defaultJSExtensions: true,
packages: packages,
map: map,
paths: paths,
meta: meta
};
System.config(config);
System.import("main");
})(this);
I load SystemJS in my index page. Here is my Index.cshtml page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Application</title>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
#Styles.Render("~/application/css/site.min.css")
<script src="#Url.Content("~/Scripts/modernizr-2.8.3.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/localStoragePolyFill.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/system.js")" type="text/javascript"></script>
</head>
<body>
#Html.AntiForgeryToken()
<div id="applicationHost" class="page-wrap">
<!-- The application is rendered here -->
</div>
<script src="#Url.Content("~/application/source/config.js")" type="text/javascript"></script>
</body>
</html>
I believe the issue is this line of code in the config
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
Where does the above line of code go if not in the config?
I have fixed the issue by splitting out the configuration and startup. I previously had the configuration and startup in the same file. My configuration file has configuration only, I have a separate startup file that actually starts the application.
Index.cshtml
#using System.Web.Optimization;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Application</title>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
#Styles.Render("~/application/css/site.min.css")
<script src="#Url.Content("~/Scripts/modernizr-2.8.3.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/localStoragePolyFill.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/system.js")" type="text/javascript"></script>
</head>
<body>
#Html.AntiForgeryToken()
<div id="applicationHost" class="page-wrap">
<!-- The application is rendered here -->
</div>
<script src="#Url.Content("~/application/source/startup.js")" type="text/javascript"></script>
</body>
</html>
Startup.js
// make sure we can load AMD files
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
// fire startup
window.require(["application/source/config.js"], function () {
// start app once config is done loading
System.import("main");
});
config.js
System.config({
baseURL: "application/source",
defaultJSExtensions: true,
packages:{
pages: {
main: 'views/*.html',
format: 'amd',
defaultExtension: 'html'
}
},
map: {
text: "../Scripts/text.js",
app: "app.js",
main: "main.js",
aes: "../../../Scripts/aes.js",
jquery: "../../../Scripts/kendo/2016.3.914/jquery.min.js",
kendo: "vendor/kendo/kendo.js",
DataTables: "../../../Scripts/DataTables/datatables.js",
k: "../../../Scripts/kendo/2016.3.914/",
bootstrap: "../../../Scripts/bootstrap.js",
lodash: "../../../Scripts/lodash.js",
moment: "../../../Scripts/moment.js",
ajaxSetup: "security/ajaxSetup.js",
q: "../../../Scripts/q.js",
toastr: "../../../Scripts/toastr.js",
wizards: "viewmodels/shared",
'kendo.core.min': "../../../Scripts/kendo/2016.3.914/kendo.core.min.js"
},
paths: {
'kendo.*': "../../../Scripts/kendo/2016.3.914/kendo.*.js",
jquery: "../../../Scripts/kendo/2016.3.914/jquery.min.js",
bootstrap: "../../../Scripts/bootstrap.js"
},
meta: {
app: { deps: ["kendo", "jquery"] },
main: { deps: ["jquery"] },
jquery: { exports: ["jQuery", "$"], format: "global" },
kendo: { deps: ["jquery"] },
bootstrap: { deps: ["jquery"] },
'kendo.core.min': { deps: ["jquery"] },
DataTables: { deps: ["jquery"], exports: "$.fn.DataTable" },
toastr: { deps: ["jquery"] }
}
});
I am not sure that this is the correct solution, but it did solve the "window not defined" issue.
I'm using r.js to minify js files in cordova based project. Unminified code is working fine, but after minifying nothing is working, not even console.log is working(which was placed in first line of the files which was loaded from index.html file), not even single error is being thrown.
So, I wanted to check whether minified code is throwing any errors at all even though if unminified code has errors. So, I changed some code(by changing object name to appp from app, and calling app.initialize) so that i can get an error in console(in unminified version). As expected I'm getting error in console with unminified version of code, where as minified version of same code(which has error) is not throwing any error.
I should be getting errors in minified code,even though the error is understable.First off I'm not getting any errors.So I don't know why nothing is working after minification, If i get some errors then I can find what exactly the problem with minified code.I don't know why this is happening.
Is anything I'm doing wrong here?
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' https://* 'unsafe-inline' 'unsafe-eval'"/>
<title>Title</title>
</head>
<body>
<div id="mainContainer">
<!-- rootviewTpl -->
</div>
<div id="modals-demo">
<div class="row">
<div class="col s12">
<div id="modal" class="modal"></div>
</div>
</div>
</div>
<div class="loader" id="loader">
</div>
<script type="text/javascript" src="cordova.js"></script>
<script src="lib/js/lock-7.10.3.js"></script>
<script src="lib/js/winstore-jscompat.js"></script>
<script src="lib/js/jwt-decode.min.js"></script>
<script type="text/javascript" src="js/config-variables.js"></script>
<script data-main="js/index.js" src="lib/js/require-2.0.0.js"></script>
</body>
</html>
index.js
define([
"./config"
], function(){
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
require(["js/database/FTMobileDatabase"]);
}
};
app.initialize();
});
config.js:
requirejs.config({
baseUrl: "lib/js",
paths: {
js: "../../js",
templates:"../../templates",
jquery:"jquery.min",
underscore:"underscore.min",
backbone:"backbone",
handlebars:"handlebars",
marionette:"backbone.marionette.min",
d3: "d3",
"d3.chart": "d3.chart",
//materialze library
velocity:"velocity.min",
hammerjs:"hammer.min",
materialize:"materialize.min",
//date libraries
moment:"moment",
hbs: 'require-handlebars-plugin/hbs'
},
shim:{
"jquery":{
deps:[],
exports:"jquery"
},
"underscore": {
deps:[],
exports: "_"
},
"backbone": {
deps: ["jquery", "underscore"],
exports: "Backbone"
},
"marionette":{
deps:["backbone"],
exports:"Marionette"
},
"handlebars":{
deps:[],
exports:"Handlebars"
},
"d3": {
deps:[],
exports: "d3"
},
"d3.chart": {
deps: ["d3"],
exports: "d3Chart"
},
"materialize":{
deps:["jquery","velocity","hammerjs"],
exports:"materialize"
},
"moment":{
deps:[],
exports:"moment"
},
hbs: { // optional
helpers: true, // default: true
templateExtension: 'hbs', // default: 'hbs'
partialsUrl: '' // default: ''
}
},
waitSeconds: 0
});
build.json:
({
appDir: "./www",
dir:"./www",
mainConfigFile:"./www/js/config.js",
modules:[
{
name:"js/index",
include:[
"js/database/FTMobileDatabase"
],
exclude:[
"js/config"
]
}
],
preserveLicenseComments: false,
allowSourceOverwrites: true,
keepBuildDir:true
})
I'm working on improving the tests for jquery-csv (jquery plugin).
I can currently run a full suite of tests (ie mocha/chai) from the command line with no problems. I'm having issues figuring out how to use require.js to load dependencies so I can extend the test runner to work with mochaphantomjs tests.
The HTML used to load RequireJS:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script data-main="scripts/app" src="scripts/require.js"></script>
</body>
</html>
The RequireJS module:
require.config({
baseUrl: '/',
paths: {
'jquery' : '../../node_modules/jquery/dist/jquery',
'jquery-csv' : '../../src/jquery.csv',
'mocha' : '../../node_modules/mocha/mocha',
'chai' : '../../node_modules/chai/chai',
},
shim: {
'mocha': {
exports: 'mocha'
},
'chai': {
exports: 'chai'
},
'jquery-csv' : {
deps: ['jquery'],
exports: 'jQuery.fn.csv',
}
},
});
define(function(require) {
require('jquery');
require('jquery-csv');
// chai setup
var chai = require('chai');
var expect = chai.expect();
var should = chai.should();
// mocha setup
var mocha = require('mocha');
mocha.setup('bdd');
mocha.reporter('html');
mocha.bail(false);
require(['test.js'], function(require) {
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
}
else {
mocha.run();
}
});
});
Note: The define function is using the CommmonJS style.
The error I'm getting is:
Uncaught Error: Module name "../src/jquery.csv.js" has not been loaded yet for context: _. Use require([])
AFAIK, the shim should have fixed this issue by loading jQuery first and attaching the plugin to it.
I'm pretty new to RequireJS, is there something obvious I'm missing?
Try to add your "jquery-csv" as dependency in:
require(['test.js', 'jquery', 'jquery-csv'], function(require, $) {
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
}
else {
mocha.run();
}
});
I need some help with the concept of only loading modules when they are needed using requireJS
this is my main.js
require(['jquery', 'path/somemodule'],
function($, somemodule) {
$(document).ready(function() {
somemodule.init()
})
})
and in the somemodule.js
define(['jquery', 'path/someothermodule'], function ($, someothermodule) {
"use strict";
var somemodule;
somemodule = {
init: function () {
someothermodule.init()
}
}
return somemodule;
)}
right now somemodule.js and someothermodule.js is loaded on all pages. How do I only load it when it's needed?
When you require a module2 from module1 using the standard define() syntax module1 will not load/run until module2 has been fully loaded. That looks like this:
// inside module1
define(['module2'], function(mod2) {
// we don't get here until AFTER module2 has already been loaded
});
An alternative to lazy-load module2 looks like this:
// inside module1
define([], function() {
require(['module2'], function(mod2) {
// we don't get here until AFTER module2 has already been loaded
});
// but we DO get here without having loaded module2
});
Now you have to program somewhat carefully to make sure you don't run into any issues with asynchronicity.
In your case you can modify your main.js file
require(['jquery'],
function($) {
// jquery is loaded, but somemodule has not
if(thisPageNeedsSomeModule) {
require(['path/somemodule'],
function(somemodule) {
// now somemodule has loaded
$(document).ready(function() {
somemodule.init()
})
});
}
})
Your main.js file will load any file paths provided to it, so long as other elements of your application specify them as dependencies. See my example main.js file:
require.config({
paths: {
'app': 'app',
'underscore':'bower_components/underscore/underscore-min',
'backbone':'bower_components/backbone/backbone-min',
'marionette':'bower_components/backbone.marionette/lib/backbone.marionette.min',
'jquery': 'bower_components/jquery/jquery.min',
'tpl':'bower_components/requirejs-tpl/tpl',
'bootstrap':'bower_components/bootstrap/dist/js/bootstrap.min',
'leaflet':'bower_components/leaflet/leaflet',
'leaflet.markercluster':'bower_components/leaflet/leaflet.markercluster',
},
shim: {
'underscore': {
exports: '_'
},
'leaflet': {
exports: 'L'
},
'leaflet.markercluster': {
deps: ['leaflet']
},
'backbone': {
deps: ['underscore']
},
'marionette': {
deps: ['backbone']
},
'jquery': {
exports: '$'
},
'bootstrap': {
deps: ['jquery']
},
'app': {
deps: ['jquery', 'leaflet','bootstrap', 'leaflet.markercluster', 'marionette', 'tpl']
},
'app.elem': {
deps:['app']
},
'app.api': {
deps:['app']
}
}
})
require(['app','app.api','app.elem'], function() {
App.start();
})
And my initial application file:
define(['router', 'collections/moments'], function(router, momentCollection) {
// Boot the app!
App = new Marionette.Application();
App.LocResolve = false; // Have we resolved the user's location?
App.Locating = true; // Are we actively tracking the user's location?
App.FileReader = window.FileReader ? new FileReader : null;
App.Position = null; // Instant access to Lat & Lng of user.
App.MomentsRaw = null; // Keep cached copy of returned data for comparison.
App.Moments = new momentCollection; // Current collection of moments.
App.Markers = new L.MarkerClusterGroup(); // Create Marker Cluster Group
App.View = null; // Current view.
// Marionette Regions
App.addRegions({
header: '#header',
map: '#map',
list: '#list',
modal: '#modal',
});
return App
})
I noticed that you aren't passing in a configuration object - is this intentional? If you use R.js, the build optimizer, it will automatically remove unused vendor files for you.
In short, sets paths to your vendor files in the require.js config, then call upon them via define() whenever you need a particular asset. This will ensure that only files you need are used. Hope this helps!
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']
}
}