简体   繁体   中英

How to use JavaScript classes in different files from HTML and still work on IOS?

I am currently in a situation where I need to use classes from JavaScript within different js files. In this case, I have a class called Panel within the file js/radar-home.js . This is how I currently use the class from within my HTML file:

<script src="{{ asset('js/radar-home.js') }}"></script>
<script>
        try{
            var panel1 = new Panel(args);
        catch(err){
            alert("Internal Error - " + err);
        }
</script>

This method works perfectly fine on Windows and Android. It also works on all the browsers I tested, including Chrome. However, when loading this on my iPhone or iPad on Safari, Chrome, Firefox, and the WebDebug app, I get an alert with the message: Internal Error - RefrenceError: Can't find variable: Panel .

My environment:

  • PHP 7.3.21
  • Laravel 6.18.25
  • On an Ubuntu 20.04 server
  • The source appears identical on both ios and windows browsers.
  • CloudFlare (proxied) - However, before I set this up, I still have the exact same issue as well as when I was using HTTP and not HTTPS.

Any help is much appreciated.

EDIT: I have placed a function within radar-home.js not wrapped by a class. This function runs without error on desktop, but it errors on IOS. Output: RefrenceError Can't find variable: testing123 ( testing123() was the test function I made).

You need to execute the code when the DOM is ready. The code is being executed before the radar-home.js is loaded to the page. Try something like:

    <script src="{{ asset('js/radar-home.js') }}"></script>
    <script>
      if(document.readyState === "loading") document.addEventListener('DOMContentLoaded', func); else func();
    
      function func(){
          try{
                var panel1 = new Panel(args);
            } catch(err){
                alert("Internal Error - " + err);
            }
      }
    </script>

So it seems the solution to this is something that I probably should have investigated earlier on. This issue occurred only on IOS devices.

Essentially, the scripts were failing to load because of syntax errors or miscellaneous errors which IOS does not parse correctly. Unlike Chrome, Firefox, and many other browsers which do their best to read the JavaScript, IOS is very picky.

After fixing all errors using a JavaScript validator (asides from ES6 errors), everything worked flawlessly on IOS.

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