1
votes

I'm converting a Bootstrap template into a WordPress theme (my first), and I'm struggling to successfully call all my scripts, which worked fine before WordPress.

I'm getting the following error for a script that sits in header.php:

Uncaught ReferenceError: $ is not defined

Script:

<script>
    $(window).on('beforeunload', function() {
        $(window).scrollTop(0);
    });
</script>

I tried using jQuery instead of $, which worked to fix a few other scripts, but then it told me jQuery wasn't defined.

I'm also attempting to call the webshim polyfill, but it's saying it's not defined:

Uncaught ReferenceError: webshim is not defined

Script:

<script>
    webshim.setOptions('forms', {
        replaceValidationUI: true,
        lazyCustomMessages: true
    });

    //start polyfilling
    webshim.polyfill('forms');
</script>

This script is also in header.php. The only thing I can think of is that WordPress is loading jQuery after my scripts, but I'm trying to avoid manually calling it. Should I move these scripts into footer.php?

Lastly, I'm referencing two Google web fonts via @import, but neither are loading. I couldn't find the font URLs to use @font-face instead, so I'm not sure what the best method is for WordPress.

All of my main JS files are called in functions.php, except for these initialisation scripts. Let me know if I need to provide more details.

Any help would be appreciated!

1
form here wordpress.org/support/topic/jquery-library-not-loading -- The $ alias is problematic because several libraries use it. To avoid the problem WordPress loads jQuery in "no conflict" mode. That means that the $ alias doesn't work and you have to load jQuery like David Gwyer did, defining the $ alias in a limited scope, or use jQuery.* every time you want to call a jQuery function. That is why you are having trouble with $. - Tasos
I tried defining the $ alias, and it returns the same error: jQuery(window).on('beforeunload', function($) { $(window).scrollTop(0); }); - Mario Parra
Also, I fixed the CSS/fonts issue by changing the order of my stylesheets in functions.php. - Mario Parra
Hi - don't put scripts in your header file. That's why you are having problems. You need to add them "the WordPress Way", which means using wp_enqueue_script in your theme's functions.php file. - random_user_name

1 Answers

0
votes

You can try this:

(function($) {
  $(window).on('beforeunload', function() {
     $(window).scrollTop(0);
  });
}(jQuery));