Search code examples
javascriptmethodnotfound

Javascript External Method Not Found


I have a html page with this on it.

var accountid = getParameterByName("AccountId");
var account = null;

if (accountid != null)
{
    account = GetEntity("Account", accountid, "Name, piv_BusinessUnit, AccountId");
}

At the bottom of that same page is this

<script src="js/datasource.CRM.js"></script>

Within that file is this

function GetEntity(logicalName, id, columnSet)
{
    return RunQuery(logicalName + "Set?&$filter="+logicalName+"Id eq guid'{" + id + "}'" + "&$select="+columnSet);
}

When running the page I get this error

Uncaught ReferenceError: GetEntity is not defined

Does anyone know any reason why a Javascript function is not found when it is there???


Solution

  • When including script tags that loads external scripts, they are only parsed as encountered in the DOM, and as such hoisting won't work across script tags.

    In other words, you have to include the script, before actually trying to use it.

    Here's the classis example, using jQuery before it's included, and failing

    <script type="text/javascript">
      $('#epic fail').addClass('wont_work'); // $ is not defined error
    </script>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>