Only in Safari: ReferenceError Can't find variable
Asked Answered
I

3

9

Many of my scripts look like this:

if (...) {

    const myvariable1 = document.querySelector('.class-1');
    const myvariable2 = document.querySelector('.class-2');

    function someFunction() {

        // Do something with myvariable1 or myvariable2

    }

    someFunction();

}

They work fine on Chrome, Firefox, Edge and Opera but on Safari I get the error:

ReferenceError: Can't find variable myvariable1

Workaround

If I declare the constants before the if statement the code works...

const myvariable1 = document.querySelector('.class-1');
const myvariable2 = document.querySelector('.class-2');

if (...) {

    function someFunction() {

        // Do something with myvariable1 or myvariable2

    }

    someFunction();

}

...but I don't understand why and I don't what to make the constant globally available.

Maybe someone can explain to me that Safari-only-behavior.

Inculcate answered 31/5, 2021 at 10:15 Comment(0)
B
9

This weird behaviour is explained in Block-level functions in non-strict code - MSN.

Enable strict mode will solve this problem.

Blanket answered 9/7, 2021 at 10:21 Comment(1)
Workaround: Instead of function someFunction() {} write var someFunction = function() {}. This works for my case.Inculcate
S
1

Strict mode is already enabled in jquery and messing with it didn't solved the problem for me in Safari.

Using var function_name = function_name() {} work sometimes, but when reloads the error comes back.

The only thing that solved for me is removing the "async" from the load of my js file of functions.

Was

<script async src="js/header-functions.js"></script>

Then this solved

<script src="js/header-functions.js"></script>

Shot answered 21/7, 2022 at 18:52 Comment(0)
P
0

To me it solved to ensure that function is called once all the DOM elements of the page are ready to be used.

I wrapped script in:

    $(function () {
      //do
    });
Pliam answered 13/12, 2022 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.