soundmanager2.js + require.js not working with firefox + adblock plus - javascript

can't get the following test to work with Firefox 22.0 when AdBlock Plus is enabled. Works just fine on Chrome + when I've disabled adblock. It also works when I'm loading the scripts with script tags instead of requirejs.
./index.html:
<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<!--<link rel="icon" type="image/png" href="img/icon.png"/>-->
<!--<script src="js/lib/jquery.js"></script>-->
<script data-main="js/main" src ="require.js"></script>
<!--
<script src="js/lib/soundmanager2.js"></script>
<script src="js/test.js"></script>
-->
<title></title>
</head>
<body>
<div id="stop" style="cursor:pointer;"> stop</div>
</body>
</html>
./js/main.js:
require.config({
paths:{
jquery:"lib/jquery",
underscore:"lib/underscore",
soundmanager2:"lib/soundmanager2"
/*backbone:"lib/backbone",
detectmobilebrowser:"lib/detectmobilebrowser"*/
},
shim: {
'underscore': {
exports: '_'
},
'soundmanager2':{
exports:"soundManager"
}
}
});
define(['jquery','underscore',"soundmanager2"],
function($,_,soundManager){
alert("hep");
window.soundManager=soundManager;
soundManager.setup({
url: 'swf',
useHTML5Audio:true,
preferFlash: false, // prefer 100% HTML5 mode, where both supported
onready: function() {
alert('SM2 ready!');
/*
soundManager.createSound({
id: 'mySound',
url: './test/test.mp3',
autoLoad: true,
autoPlay: false,
onload: function() {
soundManager.play('mySound');
},
volume: 50
});
*/
},
ontimeout: function() {
alert('SM2 init failed!');
},
defaultOptions: {
// set global default volume for all sound objects
volume: 100
}
});
$("#stop").on("click",function(){
alert("stop");
soundManager.stop("mySound");
});
return soundManager;
});
No errors or anything in the console, no alerts after that initial 'hep!' one.

Classic pattern, fight with some issue for hours, give up and ask for help, find solution immediately after posting.
added
soundManager.beginDelayedInit();
after soundManager.setup() and it works now.

Use require () method of RequireJS to load a module. In the callback write your code what need. Note that parameter of function is a array contains paths that loads dependencies
require.config({
paths:{
jquery:"lib/jquery",
underscore:"lib/underscore",
soundmanager2:"lib/soundmanager2"
/*backbone:"lib/backbone",
detectmobilebrowser:"lib/detectmobilebrowser"*/
},
shim: {
'underscore': {
exports: '_'
},
'soundmanager2':{
exports:"soundManager"
}
}
});
require(['jquery','underscore',"soundmanager2"],function($,_,soundManager){
alert("hep");
window.soundManager=soundManager;
soundManager.setup({
url: 'swf',
useHTML5Audio:true,
preferFlash: false, // prefer 100% HTML5 mode, where both supported
onready: function() {
alert('SM2 ready!');
/*
soundManager.createSound({
id: 'mySound',
url: './test/test.mp3',
autoLoad: true,
autoPlay: false,
onload: function() {
soundManager.play('mySound');
},
volume: 50
});
*/
},
ontimeout: function() {
alert('SM2 init failed!');
},
defaultOptions: {
// set global default volume for all sound objects
volume: 100
}
});
$("#stop").on("click",function(){
alert("stop");
soundManager.stop("mySound");
});
});

Related

React is not defined when using SystemJS

I was trying using SystemJS to load React but it didn't loaded instead throwing an error message in Console > 'React is not defined'
I've read their documentation also searching through similar questions but doesn't satisfy my need, did i miss something?
Here's is what I was tried
<!DOCTYPE html> <html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>React 18 with SystemJS</title>
<script src="dependencies/systemjs-6.12.1.min.js"></script>
<script type="systemjs-importmap"> {
"imports": {
"react" : "/react.production-18.min.js"
, "reactDOM" : "/react-dom.production-18.min.js"
} }
</script>
</head><body>
<div id="root">
<script type="systemjs-module">
System.import('react');
System.import('reactDOM');
class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
} }
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));
</script>
</div></body></html>
Edit1: I'm using SystemJS version 6.12.1
You need a bit more configuration to get it going. It is also recommended to keep react code in separate files.
Full working example here.
SystemJS configuration for react:
System.config({
baseURL: '//npm.jspm.io/',
// CDN resolves
paths: {
'npm:*': '//npm.jspm.io/*',
'unpkg:*': '//unpkg.com/*',
'jsdelivr:*': '//cdn.jsdelivr.net/g/*',
'jsdelivr-npm:*': '//cdn.jsdelivr.net/npm/*'
},
meta: {
'*.scss': { loader: "sass" }
},
map: {
// The Application path
'index': INDEX + '?' + Date.now(),
// SystemJS plugins
'plugin-babel': 'unpkg:systemjs-plugin-babel#0/plugin-babel.js',
'systemjs-babel-build': 'unpkg:systemjs-plugin-babel#0/systemjs-babel-browser.js',
// 'scss': 'npm:scss',
// Application modules
'react': 'jsdelivr:react#15/react.js',
'react-dom': 'jsdelivr:react#15/react-dom.js'
},
packages: {
'https://npm.jspm.io/' : { defaultExtension: 'js' },
'https://cdn.rawgit.com/*' : { defaultExtension: false },
'https://unpkg.com/' : { defaultExtension: false },
'./index.scss' : { defaultExtension: false },
},
transpiler: 'plugin-babel',
babelOptions: {
sourceMaps: false,
stage0: true,
react: true
}
});

javascript not working when added via asset pipeline

I want to implement bootstrap themes to my rails application
http://startbootstrap.com/template-overviews/creative/
in that theme there is a file named creative.js
I have add it to my application via asset pipeline
and when I load the page and use inspect element I can see it under sources tab and I can open it
But the script not worked
but If I copy paste the code and put it in my html It worked properly
my application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require creative
//= require_tree .
creative.js
(function($) {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 51
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 100
}
})
// Initialize and Configure Scroll Reveal Animation
window.sr = ScrollReveal();
sr.reveal('.sr-icons', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 200);
sr.reveal('.sr-button', {
duration: 1000,
delay: 200
});
sr.reveal('.sr-contact', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 300);
// Initialize and Configure Magnific Popup Lightbox Plugin
$('.popup-gallery').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: 'The image #%curr% could not be loaded.'
}
});
})(jQuery); // End of use strict
my application.html.erb
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Creative - Start Bootstrap Theme</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top">
<%= yield %>
<script>
creative.js code here
</script>
</body>
</html>
change the firstline in creative.js seems to fix this problem
from
(function($) {
into
$(function() {
and the last line from })(jQuery); into });
External JS/jQuery files are loading but not executing
creative.js
$(function() {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 51
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 100
}
})
// Initialize and Configure Scroll Reveal Animation
window.sr = ScrollReveal();
sr.reveal('.sr-icons', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 200);
sr.reveal('.sr-button', {
duration: 1000,
delay: 200
});
sr.reveal('.sr-contact', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 300);
// Initialize and Configure Magnific Popup Lightbox Plugin
$('.popup-gallery').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: 'The image #%curr% could not be loaded.'
}
});
}); // End of use strict

Why am I getting this Angular-Mock error and Mocha test is not running

I'm getting the exact error as found here: (window.beforeEach || window.setup) is not a function. However the fix did not work, the author of the tutorial series here even mentioned the same fix.
Here is the Tuts+ author's fix:
Which is simply to place the angular-mock script tag after the Mochai and Chai scripts. Which I did so below:
test/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mocha Spec Runner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="../app/favicon.ico">
<link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
<link href="bower_components/mocha/mocha.css" rel="stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/mocha/mocha.js"></script>
<script src="../bower_components/chai/chai.js"></script>
<!-- see Angular-mocks is here :( -->
<script src="../bower_components/angular-mocks/angular-mocks.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="main.spec.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
My main.spec.js file
/**
* #name Mocha Test Runner
* #desc Describes and runs our dashboard tests
*/
var assert = chai.assert;
var expect = chai.expect;
// This Test is designed to fail on purpose
describe('User Login', function() {
console.log('User Login');
describe('Login Failed', function() {
console.log('Login Failed');
if ('Incorrect login should fail', function() {
module('loginController')
inject(function($injector) {
apiFactory = $injector.get('ApiFactory');
});
expect(apiFactory).to.be.an('number');
});
});
});
My Gulp tasks
gulp.task('serve', function() {
return browserSync.init({
notify : false,
port : 3333,
server: {
baseDir: ['app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
gulp.task('serve-test', function() {
browserSync.init({
notify : false,
port : 4444,
server: {
baseDir: ['test', 'app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
In your index.html file, you include the angular-mocks.js script before the call to mocha.setup('bdd'). angular-mocks.js is implemented as an immediately-invoked function expression which attempts to use window.beforeEach. (https://github.com/angular/bower-angular-mocks/blob/master/angular-mocks.js#L2586)
However, mocha.js is not immediately invoked and has to be initialized with the mocha.setup function in order to add its magic to the runtime environment.
Try reversing the order of these script tags, so that mocha.js is included and initialized before angular-mocks.js.
<script src='bower_components/mocha/mocha.js'></script>
<script src='bower_components/chai/chai.js'></script>
<script>
mocha.setup('bdd');
</script>
<script src="bower_components/angular-mocks/angular-mocks.js"></script>

Use Require.js for a script with qunit

On my book of Eric Elliot I find these three code but I can not understand like to use them:
(1)
define(['ch04/amd1', 'ch04/amd2'],
function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
// Define a public API for your module:
api = {
testResults: function () {
return testResults;
}
};
return api;
});
(2)
require(['ch04-amd'], function (amd) {
var results = amd.testResults();
test('AMD with Require.js', function () {
equal(results.test1, true,
'First dependency loaded correctly.');
equal(results.test2, true,
'Second dependency loaded correctly.');
});
});
(3)
if (typeof define === 'function') {
define([], function () {
return api;
});
}
I tried to use require.js and I write these codes but it doesn't work:
javascript\librerie\jquery.js
javascript\librerie\qunit.js
javascript\librerie\require.js
script_libro_eric_elliott.php
<!DOCTYPE html>
<html>
<head>
<title>Utilizzo della libreria Require.js</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script data-main="javascript/moduli" src="javascript/librerie/require.js">
</script>
</head>
<body>
<div>Utilizzo della libreria Require.js</div>
</body>
</html>
javascript\moduli\script_libro.js
define(['ch04/amd1', 'ch04/amd2'],
function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
// Define a public API for your module:
api = {
testResults: function () {
return testResults;
}
};
return api;
});
javascript\moduli\main.js
require(['ch04-amd'], function (amd) {
var results = amd.testResults();
test('AMD with Require.js', function () {
equal(results.test1, console.log(true),
'First dependency loaded correctly.');
equal(results.test2, console.log(true),
'Second dependency loaded correctly.');
});
});
javascript\configurazione.js
/* global requirejs */
requirejs.config({
"baseUrl": "javascript/librerie",
"paths": {
"moduli": "../moduli"
},
"shim": {
"script_libro": {
deps: ["jquery", "qunit"]
}
}
});
requirejs(["moduli/main"]);
I would like to write output strings on console so I edit Eric Elliot's script too. On my console I can only read:
Error: Script error for: moduli
http://requirejs.org/docs/errors.html#scripterror
Could you help me, please?
NEW UPDATE
I believe that the problem is in script_libro.js in fact the console find an error only in this file. I send you my new code:
script_libro_eric_elliott.php
<!DOCTYPE html>
<html>
<head>
<title>Utilizzo della libreria Require.js</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<script data-main="javascript/configurazione.js"
src="javascript/librerie/require.js">
</script>
</head>
<body>
<div>Utilizzo della libreria Require.js</div>
<div id="contenitore"></div>
</body>
</html>
javascript\moduli\script_libro.js
define(['jquery', 'qunit'], function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
api = {
testResults: function () {
return testResults;
}
};
return api;
});
javascript\moduli\main.js
require(['javascript/moduli/script_libro.js'], function (amd) {
var results = amd.testResults;
test('AMD with Require.js', function () {
equal(results.test1, true,
console.log('First dependency loaded correctly.'));
equal(results.test2, true,
console.log('Second dependency loaded correctly.'));
});
});
javascript\configurazione.js
require.config({
baseUrl: 'javascript/librerie',
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
CartellaModuli: '../moduli',
},
shim: {
script_libro: {
deps: ['qunit', 'jquery']
}
}
});
require(['CartellaModuli/main']);
Your data-main should point to a module instead of a directory. Try changing it to data-main="javascript/moduli/main".
That probably won't solve everything since you don't include your configuration in configurazione.js anywhere.

Code coverage with Dojo, Mocha and Blanket - always reporting 1 covered line

I have tried setting up Blanket.js to get reports on the code coverage of our Dojo app, which we are testing using Mocha. So far, Blanket seems to load, instrument the correct files, and it also seems to figure out which lines it should look for. However, every single file/module in the report shows up as having one line tested. It looks to me like it's the top "define" line. Here's a not minimal example, but it minimally represents our app setup and reproduces the problem.
File structure
▾ dojo-mocha-blanket/
▾ modules/
GUIWidget.html
GUIWidget.js
▾ test/
▾ lib/
blanket_mocha.js // from the blanket /dist
chai.js
mocha-blanket.js // adapter as per instructions
mocha.css
mocha.js
▾ spec/
GUIWidget.js
testrunner.html
index.html
Dojo setup
<html>
<head>
<title>Dojo-Mocha-Blanket</title>
</head>
<body>
<div id="GUIWidgetContainer"></div>
<script>
var dojoConfig = {
async: true,
baseUrl: "",
modulePaths: {
"modules": "modules"
}
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"></script>
<script>
require([
"dojo/dom",
"modules/GUIWidget"
], function (dom, GUIWidget) {
var widget = new GUIWidget({}, "GUIWidgetContainer");
});
</script>
</body>
</html>
Module to test
define([
"dojo/_base/declare",
"dijit/form/Select",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
"dijit/_WidgetBase",
"dojo/text!modules/GUIWidget.html"
], function(
declare,
Select,
_TemplatedMixin,
_WidgetsInTemplateMixin,
_WidgetBase,
template
) {
return declare("GUIWidget", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: template,
addNumbers: function(lhs, rhs) {
return lhs + rhs;
},
postCreate: function() {
this.inherited(arguments);
this.header.innerHTML = this.addNumbers(40, 2);
}
});
});
Test setup
<html>
<head>
<title>Mocha spec runner</title>
<link rel="stylesheet" href="lib/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="lib/mocha.js"></script>
<script
src="lib/blanket_mocha.js"
data-cover-adapter="lib/mocha-blanket.js"
data-cover-only="/modules"></script>
<script src="lib/chai.js"></script>
<script>
mocha.setup("bdd");
mocha.globals(["dojo", "dijit"]);
mocha.setup();
expect = chai.expect;
</script>
<script>
var dojoConfig = {
async: true,
packages : [{
name : "modules",
location : "/modules"
} ]
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"></script>
<script>
require(
{
paths: {
"spec": "/test/spec"
}
},
["spec/GUIWidget"], function() {
mocha.run();
});
</script>
</body>
</html>
The test
define([
"modules/GUIWidget"
], function(
GUIWidget
) {
describe("GUIWidget", function() {
var widget;
beforeEach(function() {
widget = new GUIWidget();
widget.startup();
});
it("Should set header to 42", function() {
expect(widget.header.innerHTML).to.equal("42");
});
it("Should add numbers", function() {
expect(widget.addNumbers(1, 2)).to.equal(3);
})
afterEach(function() {
widget.destroyRecursive();
});
});
});
Results
(larger image here)
Apologies for the long code and all the bootstrapping stuff, but I've found the setup to be non-trivial :) If anyone has any ideas of why this might be happening, I'd be all ears. Thanks!

Categories