Mutation Observer is undefined - javascript

I am attempting to fix and issue with my code. I was originally using DOMNodeRemoved and DOMNodeInserted for keeping an eye on an element within a page I am working on. They worked well but did not function in IE. So I started trying to work with a MutationObserver.
Here is my Code it's called on onPageInit(the callback writes to the console but I disabled it since IE no longer supports console):
var callback = function(allmutations){
allmutations.map( function(mr){
var mt = 'Mutation type: ' + mr.type; // log the type of mutation
mt += 'Mutation target: ' + mr.target; // log the node affected.
//console.log( mt );
})
}
mo = new MutationObserver(callback),
options = {
// required, and observes additions or deletion of child nodes.
'childList': true,
// observes the addition or deletion of "grandchild" nodes.
'subtree': true
}
alert('its alive');
mo.observe(document.body, options);
It works fine in chrome, however for some reason falls flat in IE. I get a message box during load of the page that says :
An unexpected error occurred in a script running on this page.
onPageInit(pageInit)
scriptname
JS_EXCEPTION
TypeError 'MutationObserver' is undefined
Am I doing something wrong?
Additional info:
Page is a netsuite page, running jQuery 1.7.2 (if it matters)

If you need to detect DOM insertions in IE10+ (and other browsers that don't yet support MutationObserver) You can use a trick based on listening to animationstart event for CSS animations that animate a property that doesn't affect the way your nodes look.
The technique was discovered by Daniel Buchner, you can see it described it this post by David Walsh
The code required to make it work would be something like this:
#keyframes animationName{
from { outline: 1px solid transparent }
to { outline: 0px solid transparent }
}
* {
animation-duration: 0.001s;
animation-name: animationName;
}
and
document.addEventListener('animationstart', insertionHandler, false);
The setup required for this trick to work cross-browser is quite complicated with all the prefixes and event listener names. The handler will be called for every new node and the choice of the property to animate is hard.
That's why I wrapped it in a library to make it easy to use:
https://github.com/naugtur/insertionQuery
Here's a brief usage example:
insertionQ('selector').every(function(element){
//callback on every new element
});

That method was added in IE11, therefore it won't be available if the browser is running in compatibility mode for anything other than IE11.
http://msdn.microsoft.com/en-us/library/ie/dn265034(v=vs.85).aspx

Related

IntersectionObserver on IE, Edge

IntersectionObserver is fairly new, experimental API, and at this moment is not fully supported by all browsers.
It will have many uses, but for now the most prominent one is lazy-loading your images, that is if you have them plenty on your website. It is recommended by Google if you audit your website with Lighthouse.
Now, there are several snippets around the web suggesting its usage but I think none of them are 100% vetted. For example I'm trying to use this one. It works like a charm on Chrome, Firefox and Opera but it doesn't work on IE and Edge.
const images = document.querySelectorAll('img[data-src]');
const config = {
rootMargin: '50px 0px',
threshold: 0.01
};
let observer;
if ('IntersectionObserver' in window) {
observer = new IntersectionObserver(onChange, config);
images.forEach(img => observer.observe(img));
} else {
console.log('%cIntersection Observers not supported', 'color: red');
images.forEach(image => loadImage(image));
}
const loadImage = image => {
image.classList.add('fade-in');
image.src = image.dataset.src;
}
function onChange(changes, observer) {
changes.forEach(change => {
if (change.intersectionRatio > 0) {
// Stop watching and load the image
loadImage(change.target);
observer.unobserve(change.target);
}
});
}
To be more precise, the code should recognize if browser supports IntersectionObserver and if NOT it should immediately load all images without utilizing the API and write to console that IntersectionObserver is not supported. So, the snippet above fails to do that.
As far as my investigation goes, when testing with IE 11 and Edge 15, they spit an error to console that they don't recognize forEach, despite the fact that they should support it.
I've tried to shim forEach, and even replace forEach with good old for, but I can't get this snippet to work on IE and Edge.
Any thoughts?
After some tests, I found the reason.
First, I let the observer observe document.body, it works. Then I guess the observer can't observe empty elements, so I set 1px border on the element I want to observe, and then it works.
This may be a bug on Edge, because Chrome and Firefox can both observe empty elements.

Try Catch Errors many script components - JavaScript

I have a page that contains many script components (50+) and I am getting an error when using IE at some random instance (doesn't happen in Chrome or Firefox).
"Out of Memory at line: 1"
I've done some google search too and that reveals issues with IE handling things differently to Chrome and FF. I would like to catch this error and know exactly what the cause of that script error is.
What would be the best way to use a global try-catch block on that many script components? All these script components are on the same page. Looking forward to your suggestions.
You might want to try window.onerror as a starting point. It will need to be added before the <script> tags that load the components.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
If that fails, you might try reducing the components loaded by half until the error no longer occurs. Then, profile the page (you may have to reduce further due to the demand of profiling). Look for a memory leak as #Bergi suggested. If there is in fact a leak, it will likely occur in all browsers, so you can trouble-shoot in Chrome, as well.
If that still fails to yield anything interesting, the issue may be in one particular component that was not in the set of components you were loading. Ideally, anytime that component is included you see the issue. You could repeatedly bisect the loaded components until you isolate the culprit.
Finally, forgot to mention, your home-base for all of this should be the browser's developer tools, e.g. Chrome dev tools, or if it is unique to Edge, Edge debugger.
And FYI, Edge is the browser that crashes, but that does not mean the issue is not present in Chrome or FF.
One important thing that is missing in your question is if the error happens during the page loading or initialization or if it happens after some time while you browse the page.
If it's during loading or initialization, it's probably caused by the fact that your page contains too many components and uses much more memory than the browser is willing to accept (and IE is simply the first one to give up).
In such case there is no helping but reduce the page size. One possible way is to create only objects (components) that are currently visible (in viewport) and as soon as they get out of the viewport remove them from JS and DOM again (replacing the with empty DIVs sized to the size of the components).
In case the error happens while browsing the page, it may be caused by a memory leak. You may use Process Explorer to watch the memory used by your browser and check if the memory constantly increase - which would indicate the memory leak.
Memory leak in Internet Explorer may happen because it contains 2 separate garbage collectors (aka GC): one for DOM objects and other for JS properties. Other browsers (FF, Webkit, Chromium, etc.; not sure about the Edge) contains only one GC for both DOM and JS.
So when you create circular reference between DOM object and JS object, IE's GC cannot correctly release the memory and creates a memory leak.
var myGlobalObject;
function SetupLeak()
{
myGlobalObject = document.getElementById("LeakDiv");
document.getElementById("LeakDiv").expandoProperty = myGlobalObject;
//When reference is not required anymore, make sure to release it
myGlobalObject = null;
}
After this code it seems the LeakDiv reference was freed but LeakDiv still reference the myGlobalObject in its expandoProperty which in turn reference the LeakDiv. In other browsers their GC can recognize such situation and release both myGlobalObject and LeakDiv but IE's GCs cannot because they don't know if the referenced object is still in use or not (because it's the other GC's responsibility).
Even less visible is a circular reference created by a closure:
function SetupLeak()
{
// The leak happens all at once
AttachEvents( document.getElementById("LeakedDiv"));
}
function AttachEvents(element)
{
//attach event to the element
element.attachEvent("onclick", function {
element.style.display = 'none';
});
}
In this case the LeakedDiv's onclick property references the handler function whose closure element property reference the LeakedDiv.
To fix these situations you need to properly remove all references between DOM objects and JS variables:
function FreeLeak()
{
myGlobalObject = null;
document.getElementById("LeakDiv").expandoProperty = null;
}
And you may want to reduce (or remove completely) closures created on DOM elements:
function SetupLeak()
{
// There is no leak anymore
AttachEvents( "LeakedDiv" );
}
function AttachEvents(element)
{
//attach event to the element
document.getElementById(element).attachEvent("onclick", function {
document.getElementById(element).style.display = 'none';
});
}
In both cases using try-catch is not the option because the Out of memory may happen on random places in code and even if you find one line of code where it's happened the next time it may be elsewhere. The Process Explorer is the best chance to find the situations when the memory increase and and trying to guess what may be causing it.
For example: if the memory increase every time you open and close the menu (if you have one) then you should look how it's being opened and closed and look for the situations described above.
You could check your localStorage before and after any components called.
Something like:
function getLocalStorage() {
return JSON.stringify(localStorage).length;
}
function addScript(src, log) {
if(log){
console.log("Adding " + src + ", local storage size: " + getLocalStorage());
}
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
document.body.appendChild( s );
}
function callFunction(func, log){
if(log){
console.log("Calling " + func.name + ", local storage size: " + getLocalStorage());
}
func();
}
try {
addScript(src1, true);
addScript(src2, true);
callFunction(func1, true);
callFunction(func2, true);
}
catch(err) {
console.log(err.message);
}
I hope it helps you. Bye.

How can I detect CSS Variable support with JavaScript?

The latest version of Firefox has support for CSS Variables, but Chrome, IE and loads of other browsers do not. It should be possible to access a DOM Node or write a little method which returns whether the browser supports this feature, but I haven't been able to find anything which is currently able to do this. What I need is a solution which I can use as condition to run code if the browser does not support the feature, something like:
if (!browserCanUseCssVariables()) {
// Do stuff...
}
We can do this with CSS.supports. This is the JavaScript implementation of CSS's #supports rule which is currently available in Firefox, Chrome, Opera and Android Browser (see Can I Use...).
The CSS.supports() static methods returns a Boolean value indicating if the browser supports a given CSS feature, or not.– Mozilla Developer Network
With this, we can simply:
CSS.supports('color', 'var(--fake-var)');
The result of this will be true if the browser supports CSS variables, and false if it doesn't.
(You might think that CSS.supports('--fake-var', 0) would work, but as noted in comments on this answer Safari seems to have a bug there making it fail.)
Pure JavaScript Example
On Firefox this code snippet will produce a green background, as our CSS.supports call above returns true. In browsers which do not support CSS variables the background will be red.
var body = document.getElementsByTagName('body')[0];
if (window.CSS && CSS.supports('color', 'var(--fake-var)')) {
body.style.background = 'green';
} else {
body.style.background = 'red';
}
Note that here I've also added checks to see whether window.CSS exists - this will prevent errors being thrown in browsers which do not support this JavaScript implementation and treat that as false as well. (CSS.supports was introduced at the same time CSS global was introduced, so there's no need to check for it as well.)
Creating the browserCanUseCssVariables() function
In your case, we can create the browserCanUseCssVariables() function by simply performing the same logic. This below snippet will alert either true or false depending on the support.
function browserCanUseCssVariables() {
return window.CSS && CSS.supports('color', 'var(--fake-var)');
}
if (browserCanUseCssVariables()) {
alert('Your browser supports CSS Variables!');
} else {
alert('Your browser does not support CSS Variables and/or CSS.supports. :-(');
}
The Results (all tested on Windows only)
Firefox v31
Chrome v38
Internet Explorer 11
Set a CSS style with CSS variables and proof with Javascript and getComputedStyle() if it is set...
getComputedStyle() is supported in many browsers: http://caniuse.com/#feat=getcomputedstyle
HTML
<div class="css-variable-test"></div>
CSS
:root {
--main-bg-color: rgb(1, 2, 3); /* or something else */
}
.css-variable-test {
display: none;
background-color: var(--main-bg-color);
}
JavaScript
var computedStyle = getComputedStyle(document.getElementsByClassName('css-variable-test')[0], null);
if (computedStyle.backgroundColor == "rgb(1, 2, 3)") { // or something else
alert('CSS variables support');
}
FIDDLE: http://jsfiddle.net/g0naedLh/6/
You don’t need Javascript to detect if a browser supports custom properties, unless the Do stuff... is Javascript itself. Since the thing you’re detecting support for is CSS, I assume that the stuff you’re trying to do is all CSS. Therefore, if there’s a way to remove JS from this specific problem, I would recommend Feature Queries.
#supports (display: var(--prop)) {
h1 { font-weight: normal; }
/* all the css, even without var() */
}
Feature queries test support for syntax. You don’t have to query for display; you could use any property you want. Likewise, the value of --prop need not even exist. All you’re doing is checking to see if the browser knows how to read that syntax.
(I just chose display because almost every browser supports it. If you use flex-wrap or something, you won’t catch the browsers that do support custom props but that don’t support flexbox.)
Sidenote: I prefer calling them Custom Properties because that is exactly what they are: properties defined by the author. Yes, you can use them as variables, but there are certain advantages to them as properties, such as DOM inheritance:
body { --color-heading: green; }
article { --color-heading: blue; }
h1 { color: var(--color-heading); } /* no need for descendant selectors */
I had problems getting the window.CSS.supports method to work for testing css variables in chrome 49 (even though it has native support). Ended up doing this:
var supportsCssVars = function() {
var s = document.createElement('style'),
support;
s.innerHTML = ":root { --tmp-var: bold; }";
document.head.appendChild(s);
support = !!(window.CSS && window.CSS.supports && window.CSS.supports('font-weight', 'var(--tmp-var)'));
s.parentNode.removeChild(s);
return support;
}
console.log("Supports css variables:", supportsCssVars());
Seems to work in all browsers I tested.
Probably the code can be optimised though.

How to only wait for document.readyState in IE and fire instantly for all other browsers?

I have written a CSS and Javascript lazyloader to dynamically load resources for seperate pagelets (in the way that Facebook renders a page with it's BigPipe technology).
In short an HTML frame is rendered first, then separate parts of the page are all generated asynchronously by the server. When each pagelet arrives the pagelets css is loaded first, then its innerHTML is set, then finally we load any required javascript for this pagelet and initialise it.
Everything works perfectly and perceived load time is pretty much instantaneous for any given page.
However in IE, I occasional I get Method does not support method or property when initialising the scripts.
I have solved this by checking for document.readyState before loading the scripts.
Now this isn't a huge issue but it adds on average 170ms to a pageload in chrome or firefox. Which is not needed.
function loadScripts(init){
// ensure document readystate is complete before loading scripts
if( doc.readyState !== 'complete'){
setTimeout(function(){
loadScripts(init);
}, 1 );
}
else{
complete++;
if(complete == instance.length){
var scripts = checkJS(javascript);
if(scripts.length) {
LazyLoad.js(scripts, function(){
runPageletScript();
for (var i = 0; i < scripts.length; ++i) {
TC.loadedJS.push(scripts[i]);
}
});
}
else{
runPageletScript();
}
}
}
}
What I am looking for is a modification to this script which will only implement the 'wait' in IE, if it is any other browser it will just fire straight away. I cannot use a jQuery utility like $.Browser and need it to be the tiniest possible method. I hate to use any form of browser detection but it appears as though its my only solution. That said if anyone can come up with another way, that would be fantastic.
Any suggestions would be gratefully received.
You could use JScript conditional compilation, which is only available in IE browsers (up to IE10).
Because it's a comment, it's best to place it inside new Function as minifiers might remove it, changing your code. Though in general you should avoid using new Function, in this case there's not really any other way to prevent minifiers from removing it.
Example:
var isIE = !(new Function('return 1//#cc_on &0')());
However, it seems that your main issue is that the DOM hasn't loaded yet -- make sure that it has loaded before running any loader using the DOMContentLoaded event (IE9+):
document.addEventListener('DOMContentLoaded', function () {
// perform logic here
});
Here is just another solution as the solution from Qantas might not always work. For instance on UMTS connections it could happen that providers remove comments to save bandwith (maybe they preserve conditional comments):
if(navigator.appName == 'Microsoft Internet Explorer'
&& doc.readyState !== 'complete'){
...
}

The best way of checking for -moz-border-radius support

I wanted some of those spiffy rounded corners for a web project that I'm currently working on.
I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly.
I already utilize jQuery so I looked at the excellent rounded corners plugin and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs.
I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific -moz-border-radius-* properties and if so utilize them.
The check for webkit support looks like this:
var webkitAvailable = false;
try {
webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined);
}
catch(err) {}
That, however, did not work for -moz-border-radius so I started checking for alternatives.
My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse.
My best solution yet is as follows.
var mozborderAvailable = false;
try {
var o = jQuery('<div>').css('-moz-border-radius', '1px');
mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px';
o = null;
} catch(err) {}
It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties
-moz-border-radius-topleft
-moz-border-radius-topright
-moz-border-radius-bottomleft
-moz-border-radius-bottomright
Is there any javascript/CSS guru out there that have a better solution?
(The feature request for this page is at http://plugins.jquery.com/node/3619)
How about this?
var mozborderAvailable = false;
try {
if (typeof(document.body.style.MozBorderRadius) !== "undefined") {
mozborderAvailable = true;
}
} catch(err) {}
I tested it in Firefox 3 (true) and false in: Safari, IE7, and Opera.
(Edit: better undefined test)
I know this is an older question, but it shows up high in searches for testing border-radius support so I thought I'd throw this nugget in here.
Rob Glazebrook has a little snippet that extends the support object of jQuery to do a nice quick check for border-radius support (also moz and web-kit).
jQuery(function() {
jQuery.support.borderRadius = false;
jQuery.each(['BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {
if(document.body.style[this] !== undefined) jQuery.support.borderRadius = true;
return (!jQuery.support.borderRadius);
}); });
Attribution
That way, if there isn't support for it you can fall back and use jQuery to implement a 2-way slider so that other browsers still have a similar visual experience.
Why not use -moz-border-radius and -webkit-border-radius in the stylesheet? It's valid CSS and throwing an otherwise unused attribute would hurt less than having javascript do the legwork of figuring out if it should apply it or not.
Then, in the javascript you'd just check if the browser is IE (or Opera?) - if it is, it'll ignore the proprietary tags, and your javascript could do it's thing.
Maybe I'm missing something here...
Apply CSS unconditionally and check element.style.MozBorderRadius in the script?
As you're already using jQuery you could use jQuery.browser utility to do some browser sniffing and then target your CSS / JavaScript accordingly.
The problem with this is that Firefox 2 does not use anti-aliasing for the borders. The script would need to detect for Firefox 3 before is uses native rounded corners as FF3 does use anti-aliasing.
I've developed the following method for detecting whether the browser supports rounded borders or not. I have yet to test it on IE (am on a Linux machine), but it works correctly in Webkit and Gecko browsers (i.e. Safari/Chrome and Firefox) as well as in Opera:
function checkBorders() {
var div = document.createElement('div');
div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');
for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {
if ( /border.*?-radius/i.test(div.style[stylenr]) ) {
return true;
};
return false;
};
If you wanted to test for Firefox 2 or 3, you should check for the Gecko rendering engine, not the actual browser. I can't find the precise release date for Gecko 1.9 (which is the version that supports anti-aliased rounded corners), but the Mozilla wiki says it was released in the first quarter of 2007, so we'll assume May just to be sure.
if ( /Gecko\/\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\/\d*/)[0].split('/')[1]) > 20070501 )
All in all, the combined function is this:
function checkBorders() {
if ( /Gecko\/\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\/\d*/)[0].split('/')[1]) > 20070501 ) {
return true;
} else {
var div = document.createElement('div');
div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');
for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {
if ( /border.*?-radius/i.test(div.style[stylenr]) ) {
return true;
};
return false;
};
};

Categories

Resources