Uncaught TypeError: Cannot read property ‘get_current’ of undefined error in jsom SharePoint Online

This JSOM SharePoint tutorial, we will discuss how to fix the issue: Uncaught TypeError: Cannot read property ‘get_current’ of undefined.

Recently I was working with jsom to retrieve web site details in sharepoint Online. I was using the below code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
myFunction();
});

function myFunction()
{
//Your jsom code will be here
var clientContext = new SP.ClientContext.get_current();
site=clientContext.get_web();
clientContext.load(site);
clientContext.executeQueryAsync(success, failure);
}
function success() {
alert(site.get_title());
}
function failure() {
alert("Failure!");
}

</script>

When we run the above code, I got an error as: Uncaught TypeError: Cannot read property ‘get_current’ of undefined.

Uncaught TypeError: Cannot read property 'get_current' of undefined
Uncaught TypeError: Cannot read property ‘get_current’ of undefined

To fix the issue, you can follow the below solution.

When we are working with SP.ClientContext in jsom sharepoint online, we need to make sure SP.js file is loaded before this line of code runs. So you need to call our method after sp.js loaded in the page.

For this we can use ExecuteOrDelayUntilScriptLoaded() method like below:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
ExecuteOrDelayUntilScriptLoaded(myFunction, "sp.js");
});

function myFunction()
{
//Your jsom code will be here
var clientContext = new SP.ClientContext.get_current();
site=clientContext.get_web();
clientContext.load(site);
clientContext.executeQueryAsync(success, failure);

}
function success() {
alert(site.get_title());
}
function failure() {
alert("Failure!");
}
</script>

You may like the follow SharePoint tutorials:

Once you run the code, the error “Uncaught TypeError: Cannot read property ‘get_current’ of undefined” will not come.

>