Wednesday, May 20, 2015

How to include and run a jQuery plug-in or other JavaScript code

Image result for jquery images


JavaScript is used to change the behaviour or look of the HTML elements on the page.
You may for example have a script that automatically zooms out all image links, and in order for that to work those links need to exist when the code runs.

That's why you should always include JavaScript at the very bottom of the page. Just before the closing </body> tag. This ensures that the DOM has loaded and your script is ready to interact with it. Countless times have I seen people have trouble running a script and the problem was simply that the script ran before the elements existed because the script was included in head.

There may be cases when including in the <head> is beneficial (analytics code perhaps which should probably run as soon as possible). But in most cases including it in the bottom of the page is best not only for making sure the DOM is loaded but also for performance resons.

If you have more than one script file, the order in wchich you include them also matters. For example, if you want to use a jQuery plug-in, you first have to make sure that jQuery itself is loaded. Otherwise the jQuery plug-in code will try to interact with other code that does not yet exist.

Including the two is usually not enough however. You also need to actually run the plug-in. The way that's done differs from plug-in to plug-in but it's usually something like $('ul.tabs').tabs();.
So in essence, leave <head> JS free, and the bottom of your page should look like this: 
<!-- Include jQuery first -->
    <script src="jquery.js"></script>

    <!-- Then include the plug-in -->
    <script src="jquery-plugin.js"></script>

    <!-- Finally run the plug-in -->
    <script>
            $('div').runJqueryPlugin();
    </script>

<!-- And do it at the very end to ensure that the DOM has loaded -->
</body>

0 comments: