Wednesday, December 10, 2014

require.js conflicts with chart.js when AMD loading

When attempting to use chart.js on my web site, the chart would not load correctly and the following error appeared in the browser console:
Error: Mismatched anonymous define() module: function (){
"use strict";
return Chart;
The problem arises when using an AMD loader for JavaScript modules and the fact that the chart.js source is an anonomous function (like follows):
// code in here
The solution is not to reference the chart.js in the HTML markup but to simply  require and use it when needed (when interacting with the charts) in the jQuery.
require(['path/to/Chart.js'], function(Chart){
// Use Chart.js as normal here.

// Chart.noConflict restores the Chart global variable to it's previous owner
// The function returns what was previously Chart, allowing you to reassign.
var Chartjs = Chart.noConflict();
Don't forget to remove any references to chart.js in the HTML or the errors will still occur.

No comments:

Post a Comment