0

I am working with jquery and multiple scripts that require javascript in the HTML document to function correctly (thankyou web 2.0). I am using ajax to post, $(document).ready to run functions and other multiple events etc. I am using googles minify to help the load time of the external javascript files required to run the javascript in the HTML. I am also having trouble structuring/formatting my javascript.

My questions are as follows:

  • How do I minimise the code in the HTML document?
  • Is it possible to link the javascript in the HTML document externally even if it requires $(document).ready, like my example below?
  • What is a good site or tutorial to assist me in correctly formatting my jquery/javascript as I am well aware this is incorrect and does this help load time?

Below is an example of a page where I run multiple scripts (feel free to format this correctly) and an example of what I would like to link externally and structure correctly. I am not asking for anyone to do my work for me but to simply just lead me in the right direction.

<script type="text/javascript" src="lib/js/jquery.nivo.slider.js"></script>
<script type="text/javascript" src="lib/js/jquery.fancybox.js"></script>
<script type="text/javascript" src="lib/js/jquery.jcarousel.min.js"></script>

<script type="text/javascript">

    //nivo
    $(window).load(function() { 
        $('#slider').nivoSlider({ effect: 'slideInLeft', pauseTime: 5000 });
    }); 

    //fancybox
    $(document).ready(function() {
        $('.fancybox').fancybox();
        $.fancybox.open($("#welcome"), { padding : 0 });
    });

    //subscribe
    $("#footer-subscribe-show-hide").click(function () {
        $("#footer-subscribe").animate({width:'toggle'},300);
        $(this).show("#subscribe");
    });  

    //responsive
    $(function() { 
        $('.menu-mobile-drop').click(function() {
            $('.menu-mobile').toggle(); 
        });
    });
    $(".menu-wrap").click(function() { 
        $(this).find('img').toggle();
    });

    //subscriptionAjax
    $("#subscriber").submit(function(event) {
        event.preventDefault();
        $("#footer-subscribe").fadeOut();
        var values = $(this).serialize();
        $.ajax({ 
            url: "include/subscribe.php",
            type: "post",
            data: values,
            success: function(){
                $("#footer-subscribe")
                .html(
                    "<div class='subscription-success'>You're now subscribed!</div>"
                )
                .fadeIn('slow');
            },
            error: function(){
                alert("failure"); 
                $("#footer-subscribe").html('there is error while submit');
            } 
        });
    });

    //jcarousel
    function mycarousel_initCallback(carousel) {
        carousel.clip.hover(function() { 
            carousel.stopAuto();
        }, 
        function() {
            carousel.startAuto();
        });
    };
    jQuery(document).ready(function() {
        jQuery('#mycarousel').jcarousel({
            auto: 8,
            wrap: 'last',
            initCallback: mycarousel_initCallback
        });
    });

</script>
Ken Bellows
  • 6,711
  • 13
  • 50
  • 78
User_coder
  • 477
  • 1
  • 7
  • 21
  • 7
    The answer to question 2 is "yes", which should pretty much solve the rest of them. – JJJ Aug 01 '13 at 14:38
  • The only thing that is needed is ``. Apart from that, all your JavaScript code doesn't have to be in your HTML file. – putvande Aug 01 '13 at 14:40
  • 1
    As for formatting your javascript, this tutorial helped me organize my code immensely. http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html – JeffRegan Aug 01 '13 at 14:41
  • Yes, of course you can link external files. You are already doing that with jQuery and FancyBox and Carousel. `src="url"`. This link is one of many that can help you structuring your code: http://javascript.crockford.com/code.html – Abhitalks Aug 01 '13 at 14:42
  • you can create one custom js file and move entire code to that file and just include that file in your html. – Dhaval Bharadva Aug 01 '13 at 14:44
  • jQuery is made to take the JS out of the HTML, so yes, it is possible to reduce the js code in HTML by putting it into a separate js file.... – Virus721 Aug 01 '13 at 14:44

4 Answers4

2

To minimize JavaScript in HTML, simply keep all of it out of HTML.

If you need something scripted on a page, you should add a <script src=""></script> element. There's no reason to include any raw javascript on the page directly.

If you need to select an element, make good use of [data-*] attributes, selectors, and iteration:

$('[data-foo]').each(function () {
    var $this,
        data;
    $this = $(this);
    data = $this.data('foo');
    $this.foo(data);
});
Community
  • 1
  • 1
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Just curious, why did you declare the `$this` var? you never initialize or use it. – Ken Bellows Aug 01 '13 at 14:50
  • Actually small inline javascript code can save HTTP requests. – rexcfnghk Aug 01 '13 at 14:54
  • @rexcfnghk, sure, and would never be cached, and would not be scalable, and could slow the page down (assuming the linked script uses `[defer]`). I couldn't care less about generating additional HTTP requests. AJAX generates loads of HTTP requests. Images generate loads of HTTP requests. Saving a single HTTP request for a small JS script is being penny wise and dollar foolish. Use an image format with better compression, minify your CSS and JS, and you'll save much more on page performance than including a script inline. – zzzzBov Aug 01 '13 at 14:56
1

How do I minimise the code in the HTML document?

Inline javascript code such as

<script>
    $(function () {
         alert("Hello World");
    });
</script>

can be minified by using a service (e.g. Google Closure Compiler). You can simply copy and paste your code to the UI and get the minified version.

Is it possible to link the javascript in the HTML document externally even if it requires $(document).ready, like my example below?

Yes that is certainly possible. You just need to be aware of the loading order:

<script>
    $(function () {
         alert("Hello World");
    });
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

This will not work because you are calling the document.ready function from jQuery before actually including the library.

What is a good site or tutorial to assist me in correctly formatting my jquery/javascript as I am well aware this is incorrect and does this help load time?

I will recommend using PageSpeed (available as a Chrome / Firefox extension) for analyzing potential performance issues. This extension automatically generates useful suggestions (e.g. Load order of scripts/stylesheets) that will certainly increase your web application's performance.

rexcfnghk
  • 14,435
  • 1
  • 30
  • 57
  • Thanks, was exactly what I was looking for. I am not so good with English but this answer helped me immensely! Kindest regards! – User_coder Aug 01 '13 at 15:00
0

You don't have to put your JavaScript into your HTML page. Just include it using the <script> tag.

If you really want to go deep in increasing the page load time, you can use something like Minify to compress your JS and CSS code.

Dmitry Igoshin
  • 111
  • 1
  • 3
0

jQuery offers two powerful methods to execute code and attach event handlers: $(document).ready and $(window).load. The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.

More more detail refer this post..

jQuery events .load(), .ready(), .unload()

Try this for your answer:

<script type="text/javascript" src="lib/js/jquery.nivo.slider.js"></script>
<script type="text/javascript" src="lib/js/jquery.fancybox.js"></script>
<script type="text/javascript" src="lib/js/jquery.jcarousel.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
   //nivo
        $('#slider').nivoSlider({ effect: 'slideInLeft', pauseTime: 5000 });
    //fancybox   
        $('.fancybox').fancybox();
        $.fancybox.open($("#welcome"), { padding : 0 });
    //subscribe
    $("#footer-subscribe-show-hide").click(function () {
        $("#footer-subscribe").animate({width:'toggle'},300);
        $(this).show("#subscribe");
    });  

    $('.menu-mobile-drop').click(function() {
            $('.menu-mobile').toggle(); 
        });

    $(".menu-wrap").click(function() { 
        $(this).find('img').toggle();
    });

    //subscriptionAjax
    $("#subscriber").submit(function(event) {
        event.preventDefault();
        $("#footer-subscribe").fadeOut();
        var values = $(this).serialize();
        $.ajax({ 
            url: "include/subscribe.php",
            type: "post",
            data: values,
            success: function(){
                $("#footer-subscribe")
                .html(
                    "<div class='subscription-success'>You're now subscribed!</div>"
                )
                .fadeIn('slow');
            },
            error: function(){
                alert("failure"); 
                $("#footer-subscribe").html('there is error while submit');
            } 
        });
    });

    //jcarousel
    function mycarousel_initCallback(carousel) {
        carousel.clip.hover(function() { 
            carousel.stopAuto();
        }, 
        function() {
            carousel.startAuto();
        });
    };

        $('#mycarousel').jcarousel({
            auto: 8,
            wrap: 'last',
            initCallback: mycarousel_initCallback
        });
    });

</script>
Community
  • 1
  • 1
Pank
  • 13,800
  • 10
  • 32
  • 45