简体   繁体   中英

I am getting 'Uncaught Reference Error: moment is not defined' error. How can I fix this?

I have used this js code in my laravel project for getting moment library.

        var today = moment();

        function Calendar(selector, events) {
            this.el = document.querySelector(selector);
            this.events = events;
            this.current = moment().date(1);
            this.draw();
            var current = document.querySelector('.today');
            if (current) {
                var self = this;
                window.setTimeout(function () {
                    self.openDay(current);
                }, 500);
            }
        }

I have called the js file using this script tag inside body section

<script src="moment.min.js"></script>

Now getting Uncaught ReferenceError: moment is not defined in console. moment.min.js is in the same directory. How can I fix this.`

Try this

function loadError(oError) {
  throw new URIError("The script " + oError.target.src + " didn't load 
correctly.");
}

function affixScriptToHead(url, onloadFunction) {
  var newScript = document.createElement("script");
  newScript.onerror = loadError;
  if (onloadFunction) { newScript.onload = onloadFunction; }
  document.head.appendChild(newScript);
  newScript.src = url;
}

This is because, As the script is loaded asynchronously and before loading the script into the browser you are trying to access the moment. The best way of doing this is to check if the library you are using is loaded or not you can to this by adding something link this

function loadError(oError) {
  throw new URIError("The script " + oError.target.src + " didn't load correctly.");
}

function affixScriptToHead(url, onloadFunction) {
  var newScript = document.createElement("script");
  newScript.onerror = loadError;
  if (onloadFunction) { newScript.onload = onloadFunction; }
  document.head.appendChild(newScript);
  newScript.src = url;
}

and after you will be able to refer moment refer https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM