Prepare jquery before jquery and page load

1.4k views Asked by At

I have recently discovered the new trend of including all .js script at the end of the page. From what i have read so far seems pretty ok and doable with an exception.

The way I am working is using a template like:

<html>
<head>
<!-- tags, css's -->

</head>
<body>
<!-- header -->

<div id="wrapper">
   <?php
             include('pages/'.$page.'.php');
   ?>
</div>


<!-- footer -->

<!-- include all .js -->
</body>
</html>

Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.

$('.thumbnail').click(function(){
    $('.modal-body').empty();
    var title = $(this).parent('a').attr("title");
    $('.modal-title').html(title);
    $($(this).parents('div').html()).appendTo('.modal-body');
    $('#myModal').modal({show:true});
});

But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.

I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.

Thanks!

2

There are 2 answers

0
damian On BEST ANSWER

Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.

Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:

$(document).ready(function(){
    if($('.thumbnail').length) {
        // your thumbnail code
    }
});

A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:

if($('.thumbnail').length) {
    require(['ThumbnailScript'], function(ThumbnailScript){
        ThumbnailScript.init();
    });
}
1
Ateev Chopra On

The best way you can go is create a separate file for this code. Let's name it app.js. Now you can include it under the jQuery inclusion.

<script type="text/javascript" src="app.js"></script>

This will prevent code repeat. One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:

$(document).ready(function(){
    $('.thumbnail').click(function(){
        $('.modal-body').empty();
        var title = $(this).parent('a').attr("title");
        $('.modal-title').html(title);
        $($(this).parents('div').html()).appendTo('.modal-body');
        $('#myModal').modal({show:true});
    });
})