Only in Safari: ReferenceError Can't find variable

Viewed 2557

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.

2 Answers

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>

Related