Showing posts with label JS. Show all posts
Showing posts with label JS. Show all posts

Tuesday, 31 May 2016

Testing for Javascript undefined correctly

I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is NOT a keyword in JavaScript and can in fact have a value assigned to it.

// DO NOT USE the following bad examples, they are degenerate!
var undefined = false;  // Shockingly, this is completely legal!
 
var myVal;
if (myVar === undefined) {
    alert("You have been misled. Run away!");
}
if (myVar == undefined) {
    alert("You have been misled. Run away!");
}
 
Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.

The most robust way to perform this test is:

if (typeof myVar === "undefined")
 
This will always return the correct result, and even handles the situation where myVar is not declared.

Delayed Facebook Plugin Loading

When doing some complex javascript, using the standard Facebook plugins can really slow down and interfere with your script. To control when it loads and runs you can load it in manually like so (fadeTo function is an example only of organising timing):

$('.myelement').fadeTo(800, 1, function () {
    PluginSetup();
});

function PluginSetup() {

    $.ajaxSetup({ cache: true });
    $('body').append('<div id="fb-root"></div>');
    $.getScript('//connect.facebook.net/en_US/sdk.js', function () {
        FB.init({
            version: 'v2.4'
        });
        FB.XFBML.parse();
    });
}

FB.XFBML.parse() will then run through your HTML looking for plugins (you can specify a selector too) that it needs to activate.