GithubHelp home page GithubHelp logo

chartjs / chartjs-plugin-deferred Goto Github PK

View Code? Open in Web Editor NEW
108.0 12.0 21.0 289 KB

Chart.js plugin to defer initial chart updates

Home Page: https://chartjs-plugin-deferred.netlify.app/

License: MIT License

JavaScript 92.25% TypeScript 7.75%
chartjs plugin lazy-loading

chartjs-plugin-deferred's Introduction

github travis codeclimate

Chart.js plugin to defer initial chart updates until the user scrolls and the canvas appears inside the viewport, and thus trigger the initial chart animations when the user is likely to see them.

Requires Chart.js 3.x.

Documentation

Example

new Chart(ctx, {
  // ... data ...
  options: {
    // ... other options ...
    plugins: {
      deferred: {
        xOffset: 150,   // defer until 150px of the canvas width are inside the viewport
        yOffset: '50%', // defer until 50% of the canvas height are inside the viewport
        delay: 500      // delay of 500 ms after the canvas is considered inside the viewport
      }
    }
  }
});

Development

You first need to install node dependencies (requires Node.js):

> npm install

The following commands will then be available from the repository root:

> npm run build             // build dist files
> npm run build:dev         // build and watch for changes
> npm run lint              // perform code linting
> npm run lint -- --fix     // automatically fix linting problems
> npm run docs              // generate documentation (`dist/docs`)
> npm run docs:dev          // generate documentation and watch for changes
> npm run package           // create tgz and zip archives with dist files

License

chartjs-plugin-deferred is available under the MIT license.

chartjs-plugin-deferred's People

Contributors

br0ken- avatar leelenaleee avatar simonbrunel 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

chartjs-plugin-deferred's Issues

Impossible to configure the plugin

Hi,

Can someone spot the mistake in this, the 10 seconds delay is not working, neither the yOffset, actually nothing works. The plugin is working, it renders the charts as soon as the first pixel is in the viewport, but impossible to configure it.

Thank you

                  options: {
			legend: {
				display: false
			},
			tooltips: {
				callbacks: {
					label: function(tooltipItem, data) {
						var allData = data.datasets[tooltipItem.datasetIndex].data;
						var tooltipLabel = data.labels[tooltipItem.index];
						var tooltipData = allData[tooltipItem.index];
						var total = 0;
						for (var i in allData) {
							total += allData[i];
						}
						var tooltipPercentage = Math.round((tooltipData / total) * 100);
						//return tooltipLabel + ': ' + tooltipData + ' (' + tooltipPercentage + '%)';
						return tooltipLabel + ': ' + tooltipData + '%';
					}
				}
			},
			plugins: {
				deferred: {           // enabled by default
					enabled: true,
					xOffset: 150,     // defer until 150px of the canvas width are inside the viewport
					yOffset: '500%',   // defer until 50% of the canvas height are inside the viewport
					delay: 10000        // delay of 500 ms after the canvas is considered inside the viewport
				}
			}
		}

Unable to es6 import plugin

I'm using ChartJS in my Aurelia app and it works fine. I wanted to add the deferred plugin so I've npm installed it and added the import like so:

import Chart from 'chartjs';
import 'chartjs-plugin-deferred';

The package imports properly but the code throws errors: Uncaught TypeError: Cannot read property 'helpers' of undefined.

My guess is it's because the plugin is trying to access the Chart object which I assume isn't global?

(The first few lines of code try to do the following):

var Chart = window.Chart;
var helpers = Chart.helpers;

I'm honestly a little new to using import (as opposed to just stacking <script> elements) so I might be doing something wrong, but I'd love to know what?

Edit:After further testing the plugin actually seems to work properly, but I still get that error in the console which is really annoying. Any idea what could cause it?

$exports is not defined

I use "npm run build" to get the advantage of the bundle size. In my JS file I imported the ChartDeferred as follows:

import {
  Chart,
  Tooltip,
  Colors,
  BarController,
  CategoryScale,
  LinearScale,
  BarElement,
  Legend,
  BubbleController,
  PointElement,
} from 'chart.js';
import ChartDeferred from 'chartjs-plugin-deferred';

Chart.register(
    Tooltip,
    Colors,
    BarController,
    BarElement,
    CategoryScale,
    LinearScale,
    Legend,
    BubbleController,
    PointElement,
    ChartDeferred,
);

Without the ChartDeferred, the charts are working perfectly, but with ChartDeferred imported, this error appears and I can't get rid of this:

Uncaught ReferenceError: $50e8ddfc489f09fc$exports is not defined
    so chartjs-plugin-deferred.esm.js:83
    beforeInit chartjs-plugin-deferred.esm.js:98
    beforeInit chartjs-plugin-deferred.esm.js:144
    $ helpers.core.ts:109
    _notify core.plugins.js:60
    notify core.plugins.js:42
    notifyPlugins core.controller.js:1148
    _initialize core.controller.js:251
    on core.controller.js:204
    <anonymous> cc-chart.js:42

chart.js = 4.3.0
chartjs-plugin-deferred = 2.0.0

my package.json:

{
  "name": "example",
  "version": "1.0.0",
  "license": "MIT",
  "scripts": {
    "dev": "parcel src/index.html --no-content-hash",
    "build": "parcel build src/index.html --no-content-hash"
  },
  "devDependencies": {
    "parcel": "^2.6.2"
  },
  "dependencies": {
    "@cubejs-client/core": "^0.31.0",
    "chart.js": "^4.0.0",
    "chartjs-plugin-deferred": "^2.0.0"
  }
}

Error with global plugins

I'm getting the message "e.defaults.global.plugins is undefined" when trying to use the plugin on my charts.

Any help?

TypeError: Cannot set property 'font' of null

Having issue when installed the deferred plugin and inserted as

Chart.defaults.global.defaultFontFamily = "'Nunito Sans', sans-serif";

 
chartObj = new Chart(refChart, {
        type: chartType,
        data: {
          labels: chartLabels,
          datasets: chartDataset,
        },
        plugins: [
          ChartColorSchemes,
          ChartDeferred,
        ],
        options: _merge({
          plugins: {
            colorschemes: {
              scheme: "office.Breeze6",
              custom: customColorSchema,
              fillAlpha: 1,
            },
            deferred: {
              xOffset: 150,
              yOffset: "50%",
              delay: 500,
            },
          },
        }, chartOptions),
      });

chart.js version is 2.9.3
deferred plugin version is 1.0.1

image

any clue how to solve it?

Error with global options

I was hoping to set some global deferred options with Chart.defaults.global.plugins.deferred, but it seems to be undefined.

Chart.js (v2.7.0)
chartjs-plugin-deferred (v0.3.0)

Deferred animation not working in React

Hi,

I'm using chart.js (2.7.1) / chartjs-plugin-deferred (1.0.0) / react-chartjs-2 (2.7.0). My line chart is displayed at the bottom of my page, but the animation happens immediately on page load.

Here are my options, my y-axis ticks work, so not sure why the plugins do not.

const options = {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      },
      plugins: {
        deferred: {
          enabled: true,
          xOffset: 150,
          yOffset: '50%',
          delay: 500
        }
      }
    };

Any thoughts? Do I need to import chartjs-plugin-deferred?

My current imports are:

import React from 'react';
import { Line } from 'react-chartjs-2';
import { connect } from 'react-redux';

Uncaught TypeError: Cannot read property 'ticking'

chartjs-plugin-deferred.min.js:10 Uncaught TypeError: Cannot read property 'ticking' of undefined at HTMLDocument.a (chartjs-plugin-deferred.min.js:10)

I'm getting this error in Chrome.
Plugin version: 0.3.0.
Chart.js version: 2.7.0
jQuery version: 3.2.1

I'm not that experienced with JS, but please let me know if I need to provide more information.

Having trouble getting plugin working inside of Vue.js

I can't seem to get this plugin working inside a Vuejs environment on my local computer. I'm using Chartjs 2.7.2, vue-chartjs 3.4.0, vue 2.5.17, and chartist-plugin-deferred 1.0.1

I did successfully get it to work inside of Vuejs in a jsfiddle: https://jsfiddle.net/amfischer/eywraw8t/320627/

Here is a simplified repo of the fiddle, and can't for the life of me figure this out: https://github.com/amfische/vue-chartjs-plugin-deferred

I would greatly appreciate any help.

Additional Index to Draw Count

The _drawCount seems increase the value +1 from what the array length is. The array length is 29 but _drawCount has a value of 30 which creates an undefined for when deferred looks at element.hidden. It also seems like it had the proper count and then on another render the increase happened. Taking out Deferred takes away the issue. What could be the possible cause of the plugin adding an additional index? (I am using React and react-chartjs-2)

image

image

image

Add support for an inView callbaack

I have a need to be able to set a state var once the chart is in view and the animation has started. Unfortunately I cannot rely solely on the events from the chart, I am using onComplete, but in adding this plugin, onComplete is immediately fired on startup, even if the chart isn't in view, which causes problems for me. I have yet to determine why onComplete is firing. Long story short, it would be helpful to have a callback/event like inView that fires once the chart scrolls into view. This would allow me to ignore the onComplete events until after this callback event happens.

Add method to remove event listeners/cleanup

I really don't mean to spam you :)

But while using the deferred plugin on my Aurelia SPA I've noticed that unless you view every chart on a page (at which point the plugin unwatches the chart's scroll event https://github.com/chartjs/chartjs-plugin-deferred/blob/master/src/plugin.js#L107); if you go to another page and scroll down you'll get Uncaught TypeError: Cannot read property 'offsetParent' of null from chartInViewport() (https://github.com/chartjs/chartjs-plugin-deferred/blob/master/src/plugin.js#L53 I believe).

I might be missing something, but is there a way to manually remove the events? That way I can do so in my ViewModel's detached() (or React's componentWillUnmount()) similarly to how I can destroy the ChartJS instance with chart.destroy()?

Or perhaps there's a way for the plugin itself to detect calls to chart.destroy() and clean up after itself?

Again, sorry if I simply missed this feature or am using the plugin incorrectly, all I've done is import it and add the deferred options to my chart.

Doesn't work with fullPage.js

This plugin looks great!
But as soon as I included chartjs-plugin-deferred.min.js, all of my existing charts stopped working. Could someone please provide workaround or fix for this issue?

ERR_PACKAGE_PATH_NOT_EXPORTED Server error

Version:

Stacktrace

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './helpers' is not defined by "exports" in /Users/doris/src/node_modules/chart.js/package.json
    at new NodeError (node:internal/errors:371:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:429:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:638:7)
    at resolveExports (node:internal/modules/cjs/loader:482:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at /Users/doris/src/node_modules/chartjs-plugin-deferred/dist/chartjs-plugin-deferred.js:8:89 {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

I think it's the same issues reported in other chartjs plugins:
chartjs/chartjs-plugin-annotation#819
chartjs/chartjs-plugin-zoom#709

Question about performance

Does this library help the performance of a page, or is it more about deferring animation for better user experience?

I have a page with lots of charts on it and I'm wondering if it would load faster if I use this plugin to defer the initial chart updates until the user scrolls down.

Deferred update causes an uncaught error if `canvas` is destroyed

It happens sometimes that canvas element and ctx are no longer exist during a deferred update. This causes errors like Cannot read property 'save' of null. To reproduce this behavior we have to construct a new chart and kill canvas before the delay is expired (e.g. when you navigate from one page to another without waiting for all charts to be rendered completely, including delayed updates).

Screenshot 2019-12-20 at 10 06 31
Screenshot 2019-12-20 at 10 06 48

Uncaught TypeError: e.defaults.global is undefined

Hi,

First of all thank you very much for ChartJs, it's a great tool that I've been using for more than 10 years.

FYI, I have an error using the compiled and downloaded version at https://github.com/chartjs/chartjs-plugin-deferred/releases/download/v1.0.2/chartjs-plugin-deferred.min.js:
"Uncaught TypeError: e.defaults.global is undefined"
This error disappears if I use it from the sources :
"git clone ... > npm install > npm build ..."

Thanks again.

  • Chart.js v3.7.0
  • chartjs-plugin-deferred v1.0.2
  • chartjs-plugin-datalabels v2.0.0

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.