John Smith
John Smith

Reputation: 6197

How to use jQuery sooner, if its loaded at the bottom of page?

ok, lets load jQuery at the bottom. But I need it sooner than that:

<body>
<div id="aaaa"></div>
<script>
  $('#aaa').click FAIL
</script>
</body>
<script src=jquery>

Upvotes: 0

Views: 569

Answers (3)

Jens Schreiber
Jens Schreiber

Reputation: 129

(function(){click Event here}); Last step jQuery append as Last Element for the Body for faster loading

Extern scripts for more performance und er the jquery Core

Upvotes: 2

Alejandro Iv&#225;n
Alejandro Iv&#225;n

Reputation: 4061

Even if some people don't recommend it, I do recommend loading jQuery as the first script in your website. The jQuery plugins and stuff can go at the bottom of your document without problems if you add non-intrusive code after loading them.

Instead of loading at the bottom of the <body></body> part of the document, load it in the header:

<html>
    <head>
        <title>...</title>
        <script type="text/javascript" src="jquery_file.js"></script>
        <!-- ... -->
    </head>
    <body>
        <!-- ... -->
        <a href="#" id="aaa">Click me</a>
        <!-- ... -->
        <script type="text/javascript">
            $('#aaa').click(function(e) { alert('Now this should work.'); });
        </script>
    </body>
</html>

As a sidenote, please consider not including any script inside the <body> tag. jQuery is made to be, as I said before, non-intrusive, meaning it should not be mixed with the HTML. You're doing bad practices.

Your $('#aaa').click could (and should) be called in a script outside of the body tag itself and after importing jQuery. You could perfectly include that script tag just below the one that imports the jQuery library and it should work just fine.

Upvotes: 1

Saransh Kataria
Saransh Kataria

Reputation: 1497

Either move the jquery tag up, or put the other script tag also below under where you include jquery

Upvotes: 1

Related Questions