2.6.8 • Published 4 years ago

@arisageha/react-lazyload-fix v2.6.8

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

Note

This project is now currently maintained by @ameerthehacker, please reach out to him on any issues or help.


react-lazyload Build Status npm version Coverage Status npm downloads

Lazyload your Components, Images or anything matters the performance.

Join the community on Spectrum

Demo

Why it's better

  • Take performance in mind, only 2 event listeners for all lazy-loaded components
  • Support both one-time lazy load and continuous lazy load mode
  • scroll / resize event handler is throttled so you won't suffer frequent update, you can switch to debounce mode too
  • Decorator supported
  • Server Side Rendering friendly
  • Thoroughly tested

Installation

2.0.0 is finally out, read Upgrade Guide, it's almost painless to upgrade!

$ npm install --save react-lazyload

Usage

import React from 'react';
import ReactDOM from 'react-dom';
import LazyLoad from 'react-lazyload';
import MyComponent from './MyComponent';

const App = () => {
  return (
    <div className="list">
      <LazyLoad height={200}>
        <img src="tiger.jpg" /> /*
                                  Lazy loading images is supported out of box,
                                  no extra config needed, set `height` for better
                                  experience
                                 */
      </LazyLoad>
      <LazyLoad height={200} once >
                                /* Once this component is loaded, LazyLoad will
                                 not care about it anymore, set this to `true`
                                 if you're concerned about improving performance */
        <MyComponent />
      </LazyLoad>
      <LazyLoad height={200} offset={100}>
                              /* This component will be loaded when it's top
                                 edge is 100px from viewport. It's useful to
                                 make user ignorant about lazy load effect. */
        <MyComponent />
      </LazyLoad>
      <LazyLoad>
        <MyComponent />
      </LazyLoad>
    </div>
  );
};

ReactDOM.render(<App />, document.body);

If you want to have your component lazyloaded by default, try this handy decorator:

import { lazyload } from 'react-lazyload';

@lazyload({
  height: 200,
  once: true,
  offset: 100
})
class MyComponent extends React.Component {
  render() {
    return <div>this component is lazyloaded by default!</div>;
  }
}

Special Tips

You should be aware that your component will only be mounted when it's visible in viewport, before that a placeholder will be rendered.

So you can safely send request in your component's componentDidMount without worrying about performance loss or add some pretty entering effects, see this demo for more detail.

Props

children

Type: Node Default: undefined

NOTICE Only one child is allowed to be passed.

scrollContainer

Type: String/DOM node Default: undefined

Pass a query selector string or DOM node. LazyLoad will attach to the window object's scroll events if no container is passed.

height

Type: Number/String Default: undefined

In the first round of render, LazyLoad will render a placeholder for your component if no placeholder is provided and measure if this component is visible. Set height properly will make LazyLoad calculate more precisely. The value can be number or string like '100%'. You can also use css to set the height of the placeholder instead of using height.

once

Type: Bool Default: false

Once the lazy loaded component is loaded, do not detect scroll/resize event anymore. Useful for images or simple components.

offset

Type: Number/Array(Number) Default: 0

Say if you want to preload a component even if it's 100px below the viewport (user have to scroll 100px more to see this component), you can set offset props to 100. On the other hand, if you want to delay loading a component even if it's top edge has already appeared at viewport, set offset to negative number.

Library supports horizontal lazy load out of the box. So when you provide this prop with number like 100 it will automatically set left edge offset to 100 and top edge to 100;

If you provide this prop with array like [100, 200], it will set left edge offset to 100 and top offset to 200.

scroll

Type: Bool Default: true

Listen and react to scroll event.

resize

Type: Bool Default: false

Respond to resize event, set it to true if you do need LazyLoad listen resize event.

NOTICE If you tend to support legacy IE, set this props carefully, refer to this question for further reading.

overflow

Type: Bool Default: false

If lazy loading components inside a overflow container, set this to true. Also make sure a position property other than static has been set to your overflow container.

demo

placeholder

Type: Any Default: undefined

Specify a placeholder for your lazy loaded component.

demo

If you provide your own placeholder, do remember add appropriate height or minHeight to your placeholder element for better lazyload performance.

unmountIfInvisible

Type: Bool Default: false

The lazy loaded component is unmounted and replaced by the placeholder when it is no longer visible in the viewport.

debounce/throttle

Type: Bool / Number Default: undefined

Lazyload will try to use passive event by default to improve scroll/resize event handler's performance. If you prefer control this behaviour by yourself, you can set debounce or throttle to enable built in delay feature.

If you provide a number, that will be how many ms to wait; if you provide true, the wait time defaults to 300ms.

NOTICE Set debounce / throttle to all lazy loaded components unanimously, if you don't, the first occurrence is respected.

demo

wheel

DEPRECATED NOTICE This props is not supported anymore, try set overflow for lazy loading in overflow containers.

Utility

forceCheck

It is available to manually trigger checking for elements in viewport. Helpful when LazyLoad components enter the viewport without resize or scroll events, e.g. when the components' container was hidden then become visible.

Import forceCheck:

import { forceCheck } from 'react-lazyload';

Then call the function:

forceCheck();

forceVisible

Forces the component to display regardless of whether the element is visible in the viewport.

import { forceVisible } from 'react-lazyload';

Then call the function:

forceVisible();

Scripts

$ npm run demo:watch
$ npm run build

Who should use it

Let's say there is a fixed date picker on the page, when user picks a different date, all components displaying data should send ajax requests with new date parameter to retreive updated data, even many of them aren't visible in viewport. This makes server load furious when there are too many requests in one time.

Using LazyLoad component will help ease this situation by only updating components visible in viewport.

Contributors

  1. lancehub
  2. doug-wade
  3. ameerthehacker

License

MIT

acceptsBase64abbrevacornafterajv-keywordsajvamdefineacorn-jsxansi-stylesansi-escapesanymatchansi-regexaria-queryargparsearr-diffarr-flattenarray-flattenarray-includesarr-unionarray.prototype.findarray-uniquearray.prototype.flatarraybuffer.sliceassertasapassign-symbolsassertion-errorast-types-flowasync-eachatobasyncbabel-helper-bindify-decoratorsbabel-helper-builder-binary-assignment-operator-visitorbabel-helper-builder-react-jsxbabel-code-framebabel-helper-explode-classbabel-helper-define-mapbabel-helper-call-delegatebabel-generatorbabel-helper-explode-assignable-expressionbabel-helper-function-namebabel-helper-get-function-aritybabel-helper-hoist-variablesbabel-helper-optimise-call-expressionbabel-helper-regexbabel-helper-remap-async-to-generatorbabel-helper-replace-supersbabel-messagesbabel-helpersbabel-plugin-syntax-async-generatorsbabel-plugin-check-es2015-constantsbabel-plugin-syntax-async-functionsbabel-plugin-syntax-class-constructor-callbabel-plugin-syntax-class-propertiesbabel-plugin-syntax-decoratorsbabel-plugin-syntax-dynamic-importbabel-plugin-syntax-do-expressionsbabel-plugin-syntax-exponentiation-operatorbabel-plugin-syntax-export-extensionsbabel-plugin-syntax-flowbabel-plugin-syntax-jsxbabel-plugin-syntax-object-rest-spreadbabel-plugin-syntax-function-bindbabel-plugin-syntax-trailing-function-commasbabel-plugin-transform-async-generator-functionsbabel-plugin-transform-async-to-generatorbabel-plugin-transform-do-expressionsbabel-plugin-transform-class-propertiesbabel-plugin-transform-class-constructor-callbabel-plugin-transform-decoratorsbabel-plugin-transform-es2015-arrow-functionsbabel-plugin-transform-es2015-computed-propertiesbabel-plugin-transform-es2015-block-scopingbabel-plugin-transform-es2015-classesbabel-plugin-transform-es2015-destructuringbabel-plugin-transform-es2015-duplicate-keysbabel-plugin-transform-es2015-block-scoped-functionsbabel-plugin-transform-es2015-for-ofbabel-plugin-transform-es2015-function-namebabel-plugin-transform-es2015-literalsbabel-plugin-transform-es2015-modules-amdbabel-plugin-transform-es2015-modules-commonjsbabel-plugin-transform-es2015-modules-systemjsbabel-plugin-transform-es2015-modules-umdbabel-plugin-transform-es2015-object-superbabel-plugin-transform-es2015-shorthand-propertiesbabel-plugin-transform-es2015-spreadbabel-plugin-transform-es2015-parametersbabel-plugin-transform-es2015-sticky-regexbabel-plugin-transform-es2015-template-literalsbabel-plugin-transform-es2015-typeof-symbolbabel-plugin-transform-es2015-unicode-regexbabel-plugin-transform-exponentiation-operatorbabel-plugin-transform-export-extensionsbabel-plugin-transform-flow-strip-typesbabel-plugin-transform-function-bindbabel-plugin-transform-react-display-namebabel-plugin-transform-object-rest-spreadbabel-plugin-transform-react-jsxbabel-plugin-transform-react-jsx-selfbabel-plugin-transform-react-jsx-sourcebabel-plugin-transform-regeneratorbabel-plugin-transform-strict-modebabel-preset-flowbabel-polyfillbabel-preset-stage-1babel-preset-stage-3babel-preset-stage-2babel-runtimebabel-registerbabel-templatebabel-traversebabel-typesbabylonbacko2base64idbase64-arraybufferbatchbase64-jsbetter-assertbalanced-matchbig.jsblobbinary-extensionsbody-parserbrace-expansionbracesbasebufferbrowserify-zlibbuffer-frombytescache-basecallsitecaller-pathcamelcasecallsiteschain-functionchalkchardetcircular-jsonchokidarclass-utilscli-cursorcli-widthclonecocollection-visitcolor-convertcommandercolor-namecommondircomponent-bindcomponent-inheritcomponent-emitterconcat-mapconnect-history-api-fallbackconcat-streamconsole-browserifyconstants-browserifycontains-pathcontent-typeconvert-source-mapcontent-dispositioncookie-signaturecopy-descriptorcookiecore-util-iscore-jscreate-react-classcross-spawndecamelizecrypto-browserifydebugdamerau-levenshteindecode-uri-componentdeep-eqldeep-isdefine-propertiesdefine-propertydepddestroydetect-indentdoctrinedom-helpersdomain-browseree-firstemoji-regexemojis-listencodeurlencodingengine.ioengine.io-clientengine.io-parserenhanced-resolveerrnoerror-exes-abstractes-to-primitiveescodegeneslint-config-airbnb-baseeslint-import-resolver-nodeeslint-module-utilseslint-restricted-globalsescape-htmleslint-scopeespreeeslint-visitor-keysesprimaescape-string-regexpesqueryesrecurseestraverseesutilsetageventemitter3eventsexpand-bracketsexpand-rangeexpressextend-shallowexternal-editorextglobfast-json-stable-stringifyfast-deep-equalfast-levenshteinfiguresfbjsfile-entry-cachefilename-regexfinalhandlerfill-rangefind-cache-dirfind-upflat-cachefollow-redirectsfor-ownfor-inforwardedfs-readdir-recursivefragment-cachefreshfunction-bindfs.realpathfunctional-red-black-treeglob-baseget-valueglobglob-parentglobalsgraceful-fshashandlebarshas-ansihas-binaryhas-corshas-valuehas-flaghas-valueshistoryhas-symbolshoist-non-react-staticshome-or-tmphttp-browserifyhttp-errorshttp-proxyhosted-git-infohttps-browserifyiconv-liteieee754imurmurhashignoreinflightindexofinheritsinterpretinquirerinvariantis-arrayishipaddr.jsis-accessor-descriptoris-bufferis-binary-pathis-descriptoris-dotfileis-callableis-equal-shallowis-data-descriptoris-extendableis-extglobis-finiteis-date-objectis-fullwidth-code-pointis-globis-plain-objectis-numberis-posix-bracketis-primitiveis-promiseis-regexis-resolvableis-streamis-stringis-windowsis-symbolisexeisarrayisobjectjs-tokensisomorphic-fetchjs-yamljson-stable-stringify-without-jsonifyjsescjson-schema-traversejson3jsx-ast-utilsjson5load-json-filelevnkind-ofloader-utilslodashlocate-pathmap-cacheloose-envifylru-cachemap-visitmath-randommemory-fsmerge-descriptorsmedia-typermicromatchmimemethodsmime-typesmimic-fnmime-dbminimatchminimistmixin-deepmute-streammsmkdirpnanomatchnegotiatornatural-comparenode-fetchnode-libs-browserneo-asyncnormalize-package-datanormalize-pathnoptobject-assignobject-componentobject-copyobject-inspectobject-keysobject-visitobject.pickobject.assignon-finishedobject.omitobject.valuesonceoptimistoptionatoronetimeos-tmpdiros-browserifyoutput-file-syncp-limitp-locateparse-globos-homedirpakoparse-jsonp-tryoptionsparsejsonparseurlparseqsparseuripascalcasepath-browserifypath-is-absolutepath-existspath-is-insidepath-parsepath-typepath-to-regexppbkdf2-compatpifypinkiepkg-dirpinkie-promisepluralizeposix-character-classesprelude-lsprocesspreserveprivateprocess-nextick-argsprogresspromiseproxy-addrpseudomapprrpunycodeqsquerystringquerystring-es3range-parserrandomaticreact-hot-apiquery-stringreact-isread-pkgread-pkg-upraw-bodyreadable-streamregeneratereaddirpregex-notregenerator-runtimeregenerator-transformregexpu-coreregex-cacheregjsgenregjsparserrepeatingrepeat-elementremove-trailing-separatorrepeat-stringrequire-uncachedrequires-portresolveresolve-urlretresolve-fromrestore-cursorrimrafripemd160run-asyncrx-litesafe-bufferrx-lite-aggregatessafer-bufferserve-staticsemversendsafe-regexsetimmediateschedulersetprototypeofsha.jsserve-indexshebang-regexshebang-commandset-valueslashsignal-exitsnapdragon-utilsnapdragonslice-ansisocket.io-adaptersnapdragon-nodesocket.io-clientsocket.iosocket.io-parsersource-mapsource-map-resolvesource-map-urlsource-map-supportspdx-correctsource-list-mapspdx-exceptionsspdx-license-idsspdx-expression-parsestatic-extendsplit-stringsprintf-jsstream-browserifystatusesstream-cachestrict-uri-encodestring-widthstring.prototype.trimrightstring.prototype.trimleftstring_decoderstrip-bomstrip-ansitablesupports-colorstrip-json-commentstapabletime-stamptimers-browserifytmpthroughto-arrayto-object-pathtext-tableto-regextoidentifierto-regex-rangeto-fast-propertiestty-browserifytrim-righttype-checktype-istype-detectuglify-jsua-parser-jstypedarrayultronuglify-to-browserifyunset-valueunion-valueunpipeurluseutiluser-homeutil-deprecateutils-mergev8flagsurixvalidate-npm-package-licensevm-browserifywarningwebpack-dev-middlewarevarywebpack-corewatchpackwhatwg-fetchwhichword-wrapwrappywordwrapwritewindow-sizexmlhttprequest-sslwswtf-8yallistyargsyeast
2.6.8

4 years ago