Giter Club home page Giter Club logo

resize-observer-polyfill's Introduction

ResizeObserver Polyfill

Build Status

A polyfill for the Resize Observer API.

Implementation is based on the MutationObserver and uses Mutation Events as a fall back if the first one is not supported, so there will be no polling unless DOM changes. Doesn't modify observed elements. Handles CSS transitions/animations and can possibly observe changes caused by dynamic CSS pseudo-classes, e.g. by :hover.

Follows the spec and the native implementation. The size is 2.44 KiB when minified and gzipped.

Live demo (has style problems in IE10 and lower).

Installation

From NPM:

npm install resize-observer-polyfill --save-dev

From Bower: (will be removed with the next major release)

bower install resize-observer-polyfill --save-dev

Browser Support

Polyfill has been tested in the following browsers:

Build Status

NOTE: Internet Explorer 8 and its earlier versions are not supported.

Usage Example

It's recommended to use this library in the form of a ponyfill, which doesn't inflict modifications of the global object.

import ResizeObserver from 'resize-observer-polyfill';

const ro = new ResizeObserver((entries, observer) => {
    for (const entry of entries) {
        const {left, top, width, height} = entry.contentRect;

        console.log('Element:', entry.target);
        console.log(`Element's size: ${ width }px x ${ height }px`);
        console.log(`Element's paddings: ${ top }px ; ${ left }px`);
    }
});

ro.observe(document.body);

Package's main file is a ES5 UMD bundle that will be swapped with the ES6 modules version for those bundlers that are aware of the module field, e.g. for Rollup or webpack 2+.

Note: global version of the polyfill (dist/ResizeObserver.global) is deprecated and will be removed in the next major release.

Observation Strategy

As mentioned above, this implementation primarily (but not solely) relies on Mutation Observer with a fallback to Mutation Events for IE 9 and IE 10.

Speaking of Mutation Events as a fallback approach: they might not be as ugly as they are being rendered, particularly when their calls are batched, throttled and there is no need to analyze changes. Given that, they won't interrupt browser's reflow/repaint cycles (same for MutationObserver) and may even outperform Internet Explorer's implementation of MO causing little to no performance degradation. In contemporary browsers (Chrome, Firefox, etc.) Mutation Observer slows down the suite that includes 200 iterations of adding/removing elements, changing attributes and modifying text data by less than 1%. Internet Explorer gives different results with MO slowing down the same suite by 2-3% while Mutation Events show the difference of ~0.6%.

As for the reasons why other approaches, namely the iframe/object and scroll strategies, were ruled out:

  • They require the observed element to be non-statically positioned.
  • You can't apply them directly to quite a number of elements: <img>, <input>, <textarea>, <canvas>, <tr>, <tbody>, <thead>, <table>, etc. For most of them you would need to keep an extra <div> wrapper and almost all instances of the SVGGraphicsElement will be out of scope.
  • The ResizeObserver spec requires to deliver notifications when a non-empty visible element becomes hidden, i.e. when either this element directly or one of its parent nodes receive the display: none state. Same goes for when it's being removed from or added to the DOM. It's not possible to handle these cases merely by using former approaches, so you'd still need to either subscribe for DOM mutations or to continuously check the element's state.

And though every approach has its own limitations, I reckon that it'd be too much of a trade-off to have those constraints when building a polyfill.

Limitations

  • Notifications are delivered ~20ms after actual changes happen.
  • Changes caused by dynamic pseudo-classes, e.g. :hover and :focus, are not tracked. As a workaround you could add a short transition which would trigger the transitionend event when an element receives one of the former classes (example).
  • Delayed transitions will receive only one notification with the latest dimensions of an element.

Building and Testing

To build polyfill. Creates UMD bundle in the dist folder:

npm run build

To run a code style test:

npm run test:lint

Running unit tests:

npm run test:spec

To test in a browser that is not present in karma's config file:

npm run test:spec:custom

Testing against a native implementation:

npm run test:spec:native

NOTE: after you invoke spec:native and spec:custom commands head to the http://localhost:9876/debug.html page.

resize-observer-polyfill's People

Contributors

hashplus avatar que-etc avatar trysound avatar weswigham 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  avatar  avatar

resize-observer-polyfill's Issues

Singleton vs several instances

Hi!

I've decided to use this polyfill in my library, and I was wondering which would be more sensible:

  1. creating a single observer, and use that to observe all elements,
  2. creating a new instance for each element I want to observe.

More context:
I'm making a container query solution, in which I instantiate a "Container" class on each element that supports container queries.
In the module where the class is declared, I could create a new ResizeObserver instance for each element, or I could create a single resize observer, and just call observe() on that for each new element.

The difference though, is if I want to use a singleton, then I'll need to map elements to Container instances, since on each change I'll want to call an adjust method.

In summary: my dilemma is whether it's worth implementing such an Element => Container map, that the singleton resize observer would use, or should I just create a new instance for each new Container, which would have access to the aforementioned adjust method by default.

(WIP: https://github.com/ZeeCoder/container-query)

The resize-observer-polyfill plugin is able to add support for listening to css3 "animation" to change element size?

Hi,
First of all, thanks for the excellent plugin,I have applied it to my project.In your code,you use "transitionend" to listen for "CSS transition", which causes the size of the element to change, but "animation" may also cause element changes.

  // Subscription to the "Transitionend" event is used as a workaround for
  // delayed transitions. This way it's possible to capture at least the
  // final state of an element.
  document.addEventListener('transitionend', this.onTransitionEnd_);
  window.addEventListener('resize', this.refresh);

For example the following example

There is a element which use css3 animation in my container,

  #tar {
      width: 200px;
      height: 200px;
      background-color: aqua;
      border: 1px solid #ccc;
      animation: changeheight 2s ease-in 1s infinite;
    }

    @keyframes changeheight {
      0% {
        height: 300px;
      }
      50% {
        height: 200px;
      }
      100% {
        height: 300px;
      }
    }

when the inner element height change,then need to update the height of the outer 'iscroll' container, and call the refresh() method.resize-observer-polyfill plugin can't cover this situation.
Wish you reply yet,thanks!

target instanceof Element fails if element is in another window

In function ResizeObserverSPI.prototype.observe, it checks to see if target is an instance of Element. If target is from another window, this fails as it would need to check against the window.Element object for that to be true. The recommended approach is to use duck typing to check if an object is an Element. Would it be possible to change this check to use duck-typing instead?

--save-dev

In the readme, it should be --save imho.

​​TypeError: Right-hand side of 'instanceof' is not an object​​

Hi,

I am using jsdom-global when running tests and I am receiving the following error when using ResizeObserver:

​​TypeError: Right-hand side of 'instanceof' is not an object​​

I tracked down the problem to this line in the isSVGGraphicsElement function:

...
return target => (
    target instanceof getWindowOf(target).SVGElement &&
    typeof target.getBBox === 'function'
);

It seems that SVGElement is possibly not defined on the window. Would adding a check to see if SVGElement is defined interfere with the functionality here in any way?
To be honest I am not quite sure if this is an issue with the polyfill or rather with me using jsdom. I would be happy to have some guidance here and contribute if I can.

Thanks!

Angular 6 support

Hi, Thanks for this awesome resize polyfill.

Can you please confirm whether it is compatible with angular 6.x?. This polyfill is working in both chrome and IE with angular 5.x. I recently updated my app from angular5.x to 6.x. and found out that resize polyfill seems to be not working in IE. Any help.

"Unreachable code" error in ResizeObserver.js

Hey folks. I get a build warning with webpack when using this polyfill:

build │ Dropping unreachable code [./~/resize-observer-polyfill/dist/ResizeObserver.js:1010,0]
build │ Declarations in unreachable code! [./~/resize-observer-polyfill/dist/ResizeObserver.js:1010,0]

Looks like lines 1010 and 1009 should be flipped
reactobserverlines1005to1014

Resize cannot be monitored in real time

image
When used with v-chart.js (echart), the output width might be inaccurate due to the delayed rendering of the chart. Have you used debounce?

My solution is to add a setTimeout to the callback function
image

Question: Can the resize observer optionally bind to observe window resize events.

There are cases in my project where I'd like to conditionally observe resize events on specific elements or the window. Currently the ResizeObserver throws an error because the window is not of type element.

I was just curious if it was possible for this to work, otherwise I'll split the functionality into different logic blocks to do a traditional resize listener on the window in those special cases.

Question about performance

This polyfill looks great. I'm trying to decide whether it's worth using on my project.

I would appreciate a bit more context for this:

Implementation is based on the MutationObserver (no polling unless DOM changes) with a fall back to a continuous dirty checking cycle if the first one is not supported.

  • Am I right in assuming the MutationObserver method will work on all the green browsers on caniuse?
  • How efficient is the MutationObserver method really? Is it likely to cause any performance issues by monitoring all changes in the document (here), or is that pretty fast?

WeakMap Polyfill Causes Syntax Error when Uglifying

I'm running into a strange error that seems to be pointing at this polyfill's use of a WeakMap polyfill when I try to run my build with Webpack and have the Uglifier plugin enabled. There's no problem when not uglifying.

ERROR in app-4104c5d067f2dcfdce5d.js from UglifyJs
SyntaxError: Unexpected token: punc ()) [app-4104c5d067f2dcfdce5d.js:43608,18]

If I open my compiled babel output to that line, it's pointing at this line here: https://github.com/que-etc/resize-observer-polyfill/blob/master/src/shims/es6-collections.js#L15

What's interesting is it's still es6 (fat arrow) and not compiled to an es5 function:

const WeakMap = (() => {

Related Issues:
webpack/webpack#3453
souporserious/react-measure#29

Webpack build is 2.1.0-beta.22
resize-observer-polyfill is 1.2.1
react-measure is 1.4.4

Question: why the recursion in refresh?

Trying to understand this code:
` refresh() {
const changesDetected = this.updateObservers_();

    // Continue running updates if changes have been detected as there might
    // be future ones caused by CSS transitions.
    if (changesDetected) {
        this.refresh();
    }
}`

What's the benefit of calling refresh in a loop here? We are already getting notified when the transition has completed, so why check the content rectangle in a loop, especially if there are no browser events executed in between?

doubt

Can anyone tell me where is used and how it is beneficial

Rounded values of "width" and "height" properties

As for now width and height properties of a content rectangle are being rounded. This happens because clientWidth and clientHeight properties of an element that this implementation relies on are rounded as well.

And unfortunately I don't see any reliable way to solve this:

  • It's not possible to use the getBoundingClientRect method as it gives irrelevant results in cases like: inline elements, elements with CSS transformations and elements with border-box box sizing model.
  • I could have used CSS width/height properties as they contain a fractional part but yet again it's unclear on how to handle elements with box-sizing: border-box.

So, I've to leave it as it is until I can come up with a better solution.

box-sizing: border-box; Returns width without border and padding

After updating the box-sizing to border-box in my application all the existing functionality I was utilizing from this project started being inconsistent because of padding and borders.

// Normalize box-sizing.
// More info: https://css-tricks.com/box-sizing/#article-header-id-6
html {
  box-sizing: border-box;
}

Is there a way to request the width returned to include these? Or calculate these manually? I noticed some of the doc examples call out padding, but I don't see a way to calculate width + padding + borders with what is returned.

Currently I am getting the offsetWidth from the target, but asking for this property causes a reflow every time they are accessed.

[enhancement] Sync with requestAnimationFrame as per spec.

I skimmed through the code, and I see that throttle is used with a value of 20 on top of setTimeout which calls requestAnimationFrame.

I think this is problematic because it means ResizeObserver callbacks won't be in sync with code that renders things using requestAnimationFrame (for example a Three.js scene).

What will happen is that a Three.js scene (canvas with WebGL context) can be resized due to a parent container resizing, and the scene will be updated at a slower rate (due to throttle delay of 20) than the parent resize, which can cause visual disparity between the parent size and the rendered content inside the canvas.

Have you ever noticed when you resize a browser window that the edge of the window sometimes is resized before the content of the website adapts to the new window size, which causes a white gap to be displayed between the website's content and the edge of the browser window? it s quite ugly (I really don't know why they don't fix that).

This is the same type of thing that can happen due to throttle(..., 20).

I'd like to have a throttle value of 0 by default, which is not possible using setTimeout.

It would then be nice to make this throttle value configurable by the user of your ResizeObserver polyfill, with a default value of 0, and let them know that they can increase the number if they want to reduce CPU usage.

This will make your ResizeObserverController#refresh() loops in sync with the animation frames which is in sync with the spec.

Unobserve on node removal

Hey, it might be obvious, but I'm not entirely sure if I need to explicitly unobserve elements removed from the DOM to avoid memory leaks or not?

wrong export in typescript declaration

in index.d.ts library exports in default property, but in ResizeObserver.js it exports as the full module.exports object

it should be

typeof exports === 'object' && typeof module !== 'undefined' ? module.exports.default = factory()

or

export = ResizeObserver;

instead of

export default ResizeObserver;

Don't expose global ResizeObserver

We've received bug reports that TypeScript complaints Cannot find name 'ResizeObserver'.#13405. Here is the code shows how we use ResizeObserver.

I found that TypeScript removes the import ResizeObserver from 'resize-observer-polyfill' statement when generating declaration file. Here is the generated declaration file https://unpkg.com/[email protected]/lib/input/TextArea.d.ts

The reason I guess is ResizeObserver was exposed as a global interface, not sure if it's a bug of TypeScript. But as #37 (comment) said, this library is actually a ponyfill, so there is no need to expose ResizeObserver as global right?

Doesn't work in Safari

Great polyfill!

Unfortunately I just found out that it doesn't work at all in Safari.

Can you make it work in Safari?

inotify - windows incompatible module

Hey, trying to use this library, however getting this error:

λ yarn add dev resize-observer-polyfill
yarn add v1.3.2
(node:12920) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.a
llocUnsafe(), or Buffer.from() methods instead.
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
error [email protected]: The platform "win32" is incompatible with this module.
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Maybe Undo MutationEvent Fix For IE11?

I tested https://jsfiddle.net/x2r3jpuz/2/ on IE11, and it is not causing a crash for me. This is the version info for my IE11:
image

If Microsoft has apparently fixed whatever bug was causing that problem, should the code switch back to using MutationObservers instead of MutationEvents, since MDN's docs say MutationEvents are deprecated and can make DOM modifications "1.5 - 7 times slower?"

Wrong behavior for elements with dimensions less than 0.5px

Elements with dimensions less than 0.5 are considered to be empty. This happens because of the approach used to detect certain types of elements: basically we check whether clientWidth and clientHeight properties are equal to zero and return an empty rectangle if it's so. This way we can discard non-replaced inline, hidden, detached and empty elements.

But the thing is that client dimensions are being rounded and thus a rounded value < 0.5 will be 0.
Unfortunately there is not much that can be done about it. If not for this approach it would be necessary to implement separate methods for all of the above cases and it's barely possible to perform a precise and performance effective test for hidden elements (display: none case). E.g. even jQuery gives incorrect results in its' ':visible' filter considering that an element with dimensions less than 0.5 is hidden.

This issue is not planed to be fixed.

ResizeObserver not triggered for display change in web component

The ResizeObserver polyfill does not invoke callbacks for observers of elements inside of web components when display attribute changes. I've reproduced this in Safari and FF, with a small demo of the behavior that simply toggles the display: none;/ display: inline-block;. Steps to reproduce (in the demo):

  1. click the toggle button for the native case (observing simple div) - observe that the div is displayed, and that a message is written to the console from the observer callback

  2. click the toggle button for the web component case - observe that the element is displayed, but a message is not written to the console from the observer callback when using Firefox or Safari. This works as expected for Chrome.

Interesting observation - if the toggle button for the web component is clicked first, and then the native toggle is clicked second, both callback messages appear.

Trigger refresh on font load

It appears that in current implementation refresh won’t be triggered when a font is loaded, and elements’ resize caused by the font load won’t be detected.
Is this assumption correct, and if so do you plan to add a support for it?

Invalid calling object

First and foremost: Nice implementation!
Second: I really do not want to make a request for IE11 but.....

I have just started to use this to decouple our library from framework cycles (like $digest in angular) but have run into a small issue when hot-reloading while running locally. Due to our use of use strict, IE11 cannot figure out what 'this' is for the requestAnimationFrame. This does not affect the final build.

It is extremely similar to vuejs/vue#4465

Any chance you would be willing to ensure window objects are referenced? I would make a pull request but seem unable to at the moment.

Thanks!

Ability to specify window and document?

I was wondering if it would be possible to specify/pass the window and document into resize-observer-polyfill.

I will be loading my script using the FIF (Friendly iFrame) method. When I do this, I have to get the parent window and parent document. If I attempt to use the global window and global document, I'll end up with the window and document of the iframe, not the main page.

Information on FIF can be found at the following links:
https://www.facebook.com/note.php?note_id=10151176218703920
http://www.lognormal.com/blog/2012/12/12/the-script-loader-pattern/

Thanks!

How to use the module when testing in Jest/Enzyme?

Thanks for this polyfill/ponyfill. I recently discovered the ResizeObserver api and realized it was exactly what I needed to solve a problem in my app. However, I'm having trouble figuring out how to use it in a way that works both in my app and in the tests for my app.

The app is a React app written in TypeScript. I have a component that needs to use ResizeObserver in the componentDidMount lifecycle method, so the module is imported in the component as:
import ResizeObserver from 'resize-observer-polyfill';

And then used in the code like:

const ro = new ResizeObserver((entries, observer) => {...});
ro.observe(...);

Obviously leaving out the specific observer details, but this works great and does exactly what I wanted it to do in my app.

The problem is that any tests we have (the tests are also written in TypeScript using Jest and Enzyme) that mount this component fail with the following when Jest tries to run them:
TypeError: resize_observer_polyfill_1.default is not a constructor.

We tried changing how the module is imported to use the require syntax, like const ResizeObserver = require('resize-observer-polyfill'). This results in the tests working, but then we get the same error in the browser when running the Webpack'ed React app. Is there a way to use this module that will work in both Webpack'ed code in the browser and the Jest tests in Node?

I admit that I still get confused by the various JS module formats and how they interact, so I may just be doing something dumb/wrong here. If there's any more specific information needed about our specific configuration just let me know. The versions of the various libraries involved are (from package.json):

"react": "^16.2.0",
"typescript": "3.1.6",
"webpack": "^3.1.0",
"jest": "^22.4.3",
"resize-observer-polyfill": "^1.5.1"

MutationObserver in IE11 causing exceptions

I am seeing issues with this polyfill in IE11, which appear to be caused by the MutationObserver instance. I haven't been able to create an isolated reproduction, but when the issue occurs the entire browser crashes.

I was wondering if it might be feasible to add an option to disable the use of the MutationObserver? That way we could disable it conditionally in our application.

Observing the entire document for everything may be too heavy?

this.mutationsObserver_ = new MutationObserver(this.refresh);
this.mutationsObserver_.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});

Here this triggers refresh, which makes all ResizeObservers check for size changes on any change of anything in the DOM.

This seems like it may be a little heavy.

Maybe we can instead

  1. observe changes to any <style> elements in the top-level light tree.
    • call broadcastActive on all ResizeObservers in the light tree only on these changes.
  2. for each element observed with ResizeObserver, listen to attribute changes only on that element directly (as opposed to attribute changes of all elements that exist in the document).
    • call broadcastActive on the element's ResizeObservers only on these changes
  3. Repeat step 1 but inside of every shadow tree instead of the document light tree.
    1. When an element is moved from one shadow tree to another (or to the document light tree), the ResizeObserver needs to associate with a ResizeObserverController of that new tree.
  • The easy way to change ResizeObserverController is to have one per tree (light or shadow), so that we can re-associate ResizeObservers with them when elements are moved.
  • Another possibility could be that a single ResizeObserverController keeps track of all the light/shadow trees, and re-associate which tree a ResizeObserver receives refreshes from after an element has been moved.
  • Re-association might be as simple as just destroying the current ResizeObserverSPI and making a new one, and when ever a new one is made it happens relative to an element's new location in some tree, therefore the controller or SPI can traverse up the tree to determine what is the root (document or shadow root) and use the associated MutationObserver.

Currently, I don't think observing the document considers what happens in Shadow roots, right? Because a MutationObserver won't cross the boundary, because shadow roots aren't (grand)children of any element in the document, and if they are mode: 'closed' then they are not even referenced from any elements in the document.

So that's why we need a controlling mechanism in each light/shadow tree.

TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Hi, I am new to typescript and I hit a problem with resize-observer-polyfill.
When I try to make an instance of ResizeObserver I get:
TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
The error sounds like the ResizeObserver type doesn't have a construct(or) signature.

Example code:

import * as ResizeObserver from 'resize-observer-polyfill';
const observer: ResizeObserver = new ResizeObserver((
	entries: ResizeObserverEntry[],
	observer: ResizeObserver
): void => {
	// ...
});

And my typescript configuration:

{
	"compilerOptions": {
		"target": "es5",
		"module": "commonjs",
		"baseUrl" : ".",
		"rootDir": "src",
		"outDir": "lib",
		"declaration": true,
		"strict": true,
		"jsx": "react",
		"noImplicitReturns": true,
		"noImplicitThis": true,
		"noImplicitAny": true,
		"strictNullChecks": true,
		"paths": {
			"*" : ["node_modules/@types/*", "*"]
		}
	},
	"include": [
		"src"
	]
}

Thanks!

Infinite loop causes tab to crash

I originally filed this issue with ngx-bootstrap because I discovered it when triggered by their tooltips. (Actually, our users discovered it in production 😞 ) However, after much investigation, I found it was the combination of their tooltips, this library, and browser zooming that all have to come together to trigger the issue.

Here is a plnkr demonstrating the issue. Zoom the browser in or out and mouse over the buttons to lock up the browser tab as it spikes the CPU in some kind of infinite loop. You may need to experiment: for me on Chrome it locks up at 90% and 125% zoom, but not at 100% or 110%.

Here is same the issue I filed with ngx-bootstrap. I'm not sure which library is to blame, so I'm also filing this issue as well in case there is something to fix here.

How to externalise resize-observer-polyfill in Webpack

I have a currently a problem with a simple externalization in Webpack.

My module (@teronis-js/event-driven-resize-observer-polyfill) is bundled with webpack and these externals:

...
externals: {
      "@teronis-js/event-dispatcher": {
        commonjs: "@teronis-js/event-dispatcher",
        commonjs2: "@teronis-js/event-dispatcher",
        amd: "@teronis-js/event-dispatcher",
        root: ["Teronis", "EventDispatcher"],
      },
      "resize-observer-polyfill": "resize-observer-polyfill"
    }
...

The module and their dependencies are included in my frontend app like that :

...
<script src="node_modules/@teronis-js/event-dispatcher/dist/teronis-js-event-dispatcher.js"></script>
<script src="node_modules/resize-observer-polyfill/dist/ResizeObserver.js"></script>
<script src="node_modules/@teronis-js/event-driven-resize-observer-polyfill/dist/teronis-js-event-driven-resize-observer-polyfill.js"></script>
...

Current behavior when invoking the index html with scripts:
Uncaught TypeError: resize_observer_polyfill__WEBPACK_IMPORTED_MODULE_1___default.a is not a constructor

I know that the resize-observer-polyfill is not built by webpack and I think that the head of the /dist/ResizeObserver.js belongs to commonjs and amd. I may be wrong with this.

I am pretty new in the world of Webpack and so I would like to ask you how I could externalise this polyfill.

Pull `getContentRect()` into it's own module?

Do you think it would make sense to expose the getContentRect() algorithm implemented here as it's own module? There seems to be a fair amount of logic related to ensuring cross-browser compatibility that I would rather not replicate.

Typescrpt Definition do not expose global ResizeObservable.

At the moment, for Typescript to see the ResizeObservable constructor, it has to be imported from the module, however this library is meant to be a polyfill so it should expose the variable globally so the resize-observer-polyfill module can be referenced in the types property in the tsconfig.json file.

The definition file needs to be changed to look like this:

interface DOMRectReadOnly {
    readonly x: number;
    readonly y: number;
    readonly width: number;
    readonly height: number;
    readonly top: number;
    readonly right: number;
    readonly bottom: number;
    readonly left: number;
}

declare global {
    interface ResizeObserverCallback {
        (entries: ResizeObserverEntry[], observer: ResizeObserver): void
    }

    interface ResizeObserverEntry {
        readonly target: Element;
        readonly contentRect: DOMRectReadOnly;
    }

    interface ResizeObserver {
        observe(target: Element): void;
        unobserve(target: Element): void;
        disconnect(): void;
    }

    const ResizeObserver: {
        prototype: ResizeObserver;
        new(callback: ResizeObserverCallback): ResizeObserver;
    }
}

export default ResizeObserver;

Just a minor change really, moving the const ResizeObserver declaration inside the global declaration.

Firefox throws error for ResizeObserverSPI.prototype.observe function

In firefox it throws error in ResizeObserverSPI.prototype.observe function, saying TypeError: "invalid 'instanceof' operand getWindowOf(...).Element".

Try to watch getWindowOf(target), and it returns
{​ __impl4cf1e782hg__: Window, <prototype>: {…} } instead of window directly.

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.