user1956194
user1956194

Reputation: 27

How can I recognize that a JavaScript File is loaded

I have the folowing problem:

My site is loading jQuery in the head section. It has the "async" flag so it's loading asynchronisly. I have written some functions using jQuery und manipulating the content.

When I implement this functions at the end of the jQuery file, sometimes jQuery is loaded before the whole DOM of the website. That means my functions cannot find the special elements and don't do anything. If I implement this funktions at the end of the HTML file, when the DOM is already loaded, it happens that the webpage is finished but jQuery not. Then I get the error that the jQuery reference is not defined.

Has anyone an idea how i can fix this dilemma? Loading JS asynchronisly and calling functions, when DOM and JS file has been loaded?

Thanks, Jens

Upvotes: 0

Views: 133

Answers (4)

John_C
John_C

Reputation: 1176

Put all the javascript at the end of your page, jQuery first. Something like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <!-- jQuery -->
<script src="script.js"></script> <!-- your code -->
</body>
</html>

Upvotes: -1

bhamlin
bhamlin

Reputation: 5197

This isn't that difficult and doesn't require additional libraries or polling like the other answers suggest.

Script tags, including ones marked async, support an onload() function to call when they are loaded, and jQuery has the $(document).ready() method for when the DOM is loaded. You need to wait for both. So:

<script async src='jquery.js' onload='jqueryloaded()'></script>
<script>
    function jqueryloaded() {
        $(document).ready(function () {
            // all your code
        });
    }
</script>

jsfiddle example

Upvotes: 2

csha
csha

Reputation: 9614

You can use depend.js library. Include (synchronously) the depend.js file in your head element, wrap the jquery code in

Library(
 "jquery",
 function(){
  //The jQuery itself goes here
});

and wrap every script that needs jQuery by this:

Script(
 "any-name",
 ["jquery"],
 function(){
  //The script body
});

You can use it even for your libraries. If a library depends on another library, just use Library("mylib",["dependency1","dependency2"],f);, where f is the library body.

Hope it helps.

Upvotes: 0

Alex
Alex

Reputation: 10226

use require.js.

Alternatively you can write something like this, which is not best practice:

var checkforjquery = setInterval(function() {
  if (window.jQuery) {
    clearInterval(checkforjquery);
    // all your jquery functions
  }
}, 100);

Upvotes: 0

Related Questions