0

我最近发现了在页面末尾包含所有 .js 脚本的新趋势。从我目前所读的内容来看,除了例外,似乎还可以并且可行。

我的工作方式是使用如下模板:

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

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

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


<!-- footer -->

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

现在,如果我想在我的页面 http://www.bootply.com/71401上使用这个示例,我必须在我的 jquery 包含下添加以下代码。

$('.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});
});

但这意味着我要么在每个页面中使用它 - 即使我没有使用它,要么在 $page.'php' 文件中使用 php 生成它,并在包含 js 之后在模板文件中回显它。

不过,我确信,存在更好的方法,我不想从使用可能受到损害的方法开始。

谢谢!

4

2 回答 2

0

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});
    });
}) 
于 2014-06-02T08:30:44.367 回答
0

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();
    });
}
于 2014-06-02T08:33:54.457 回答