$cache[$key] = empty($arr) ? NULL : $arr; return $cache[$key]; } // 门户 获取需要在频道显示的栏目主题数据 function portal_channel_thread($fid) { global $forumlist; if (empty($fid)) return NULL; $orderby = array('tid' => 1); $page = 1; // 遍历所有在频道显示内容的栏目 $category_forumlist = channel_category($fid); $arrlist = array(); $forum_tids = array(); $tidlist = array(); if ($category_forumlist) { foreach ($category_forumlist as &$_forum) { // 频道显示数据 $arrlist['list'][$_forum['fid']] = array( 'fid' => $_forum['fid'], 'name' => $_forum['name'], 'rank' => $_forum['rank'], 'type' => $_forum['type'], 'url' => $_forum['url'], 'channel_new' => $_forum['channel_new'], ); $forum_thread = thread_tid__find(array('fid' => $_forum['fid']), $orderby, $page, $_forum['channel_new'], 'tid', array('tid')); // 最新信息按栏目分组 foreach ($forum_thread as $key => $_thread) { $forum_tids[$key] = $_thread; } unset($forum_thread); } $tidlist += $forum_tids; } unset($category_forumlist); // 获取属性对应的tid集合 list($flaglist, $flagtids) = flag_thread_by_fid($fid); empty($flagtids) || $tidlist += $flagtids; unset($flagtids); // 频道置顶 $stickylist = sticky_list_thread($fid); empty($stickylist) || $tidlist += $stickylist; // 在这之前合并所有二维数组 tid值为键/array('tid值' => tid值) $tidarr = arrlist_values($tidlist, 'tid'); // 在这之前使用$tidarr = array_merge($tidarr, $arr)前合并所有一维数组 tid/array(1,2,3) if (empty($tidarr)) { $arrlist['list'] = isset($arrlist['list']) ? array_multisort_key($arrlist['list'], 'rank', FALSE, 'fid') : array(); return $arrlist; } $tidarr = array_unique($tidarr); $pagesize = count($tidarr); // 遍历获取的所有tid主题 $threadlist = well_thread_find_asc($tidarr, $pagesize); // 遍历时为升序,翻转为降序 $threadlist = array_reverse($threadlist); foreach ($threadlist as &$_thread) { // 各栏目最新内容 isset($forum_tids[$_thread['tid']]) AND $arrlist['list'][$_thread['fid']]['news'][$_thread['tid']] = $_thread; // 全站置顶内容 isset($stickylist[$_thread['tid']]) AND $arrlist['sticky'][$_thread['tid']] = $_thread; // 首页属性主题 if (!empty($flaglist)) { foreach ($flaglist as $key => $val) { if (isset($val['tids']) && in_array($_thread['tid'], $val['tids'])) { $arrlist['flaglist'][$key][array_search($_thread['tid'], $val['tids'])] = $_thread; ksort($arrlist['flaglist'][$key]); $arrlist['flag'][$_thread['tid']] = $_thread; } } } } unset($threadlist); if (isset($arrlist['sticky'])) { $i = 0; foreach ($arrlist['sticky'] as &$val) { ++$i; $val['i'] = $i; } } if (isset($arrlist['flag'])) { $i = 0; foreach ($arrlist['flag'] as &$val) { ++$i; $val['i'] = $i; } } if (isset($arrlist['flaglist'])) { foreach ($arrlist['flaglist'] as &$val) { $i = 0; foreach ($val as &$v) { ++$i; $v['i'] = $i; } } } isset($arrlist['list']) AND $arrlist['list'] = array_multisort_key($arrlist['list'], 'rank', FALSE, 'fid'); return $arrlist; } ?>javascript - using jQuery (put at the bottom of the page) on specific page - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - using jQuery (put at the bottom of the page) on specific page - Stack Overflow

programmeradmin0浏览0评论

Because of performance purposes I put loading of jQuery scripts at the bottom of the page (just before the closing body tag).

My question is how to enable page specific scripts? I don't want to put everything inside $(document).ready method (again because of performance purposes).

Update: I'm using a template system so I put jQuery loading in the template. That way jQuery calls don't get recognized even if I put them at the end of a specific page because jQuery is not loaded at that point.

Because of performance purposes I put loading of jQuery scripts at the bottom of the page (just before the closing body tag).

My question is how to enable page specific scripts? I don't want to put everything inside $(document).ready method (again because of performance purposes).

Update: I'm using a template system so I put jQuery loading in the template. That way jQuery calls don't get recognized even if I put them at the end of a specific page because jQuery is not loaded at that point.

Share Improve this question edited Oct 13, 2009 at 8:59 Justin Johnson 31.3k7 gold badges66 silver badges89 bronze badges asked Oct 13, 2009 at 8:07 StrudelStrudel 8194 gold badges10 silver badges18 bronze badges 1
  • you really don't understand what you're asking do you? Would you like some real-time support in solving this? Then I suggest you visit chat.stackoverflow.com/rooms/17/javascript and mention the URL of this post (as a single message, just paste the URL of this window) and that you don't understand $(document).ready() – jcolebrand Commented Dec 20, 2010 at 21:33
Add a comment  | 

8 Answers 8

Reset to default 4

I'm not 100% sure what you're asking, but if it's what I think it is, the answer is that you can't have your cake and eat it too.

It seems that you've moved jQuery to the button of the page but have some elements of the page that you want to use JavaScript on, but don't want to wait for document.ready for all of the? Maybe something like the following?

<html>
<body>
   <ul id="maybe-some-menu-that-needs-js-initialization-for-example">
   ...
   </ul>
   <script>
     /* javascript goes here that uses jquery for the above menu (or whatever) 
     AND you don't want to wait for document.ready for this to happen */
   </script>
   ...
   <script src="including jquery here"></script>
   <script src="including other scripts here"></script>
</body>
</html>

If that's the case, then refer to what I said from the get-go. You'll have to move jQuery (at least the library, not necessarily all your other JavaScript) back to the top of the page. Either that or don't us jQuery for the things you don't want to wait for document.ready for.

Edit: If you want to perform actions based on the page that you are, then there are two methods, each better and more preferable then the last.

  1. Use location.pathname to determine what functionality you need.
  2. Organize your JavaScript into separate, modular files by their functionality and include only those that are needed for the specific page.

The $(document).ready() will not be overridden when using it more than once, so you can load 2 script files that both adds functionality to be run when the document is loaded.

using $(document).ready, it doesn't matter where in the page it is, as it will only execute when the DOM has finished loading. The only code that should go inside $(document).ready is code that needs to be set up when the DOM has loaded, e.g. event handlers, any effects/animations that you want to run as soon as the DOM has finished loading, etc. Other functions do not need to be in $(document).ready, such as a function used in sorting an array, named functions called when events are raised, etc.

As has been pointed out, you can have more than one $(document).ready function on a page, as what you are doing is specifying a function (named or anonymous) to execute when the ready event (a jQuery event) is raised.

EDIT:

That article that you have linked to in the comments on this answer provides and example of what you are trying to achieve. As an example, you would have a JavaScript file with the following setup to declare a global variable

var myPageLibrary = {
    homePage : {

        init : function() {
            $(document).ready(function() {
                /* page specific functions that need to run,
                   for exmaple, binding event handlers, etc */
            });
        }
    },
    aboutPage : {
        init : function() {
            $(document).ready(function() {
                /* page specific functions that need to run,
                   for exmaple, binding event handlers, etc */
            });
        }
    }
}

/* you might have functions here that are bound to events. 
   Here is an example */

function showSubMenu(e) {
    $(e.target).next('div').show();
}

function hideSubMenu(e) {
    $(e.target).next('div').hide();
}

Then in your pages, you would have the following structure (this example uses the home page)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>This is my Home Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="path-to-myPageLibrary.js"></script>
<script type="text/javascript">
    myPageLibrary.homePage.init(); 
</script>
</head>
<body>
  <!-- Page content -->
</body>
</html>

with jQuery script file referenced first, followed by myPageLibrary script file, followed by the script block calling myPageLibrary.homePage.init();

If I understand correctly, you need to put some javascript code that calls jquery in the middle of your page. But your jquery include is at the bottom of the body. You can do this by calling the jquery at the window.load event. This event fires after all async scripts have loaded and executed. e.g.:

<body>
    <script>
        $("#myElem").val(); // fails, "$" not defined
        window.addEventListener("load", function(evt) {
            $("#myElem").val(); // ok, jquery is loaded
        });
    </script>
    <span id="myElem>hi</span>
    <script src="//cdn.jquery.com"></script>
</body>

This allows you to call jQuery plugin methods in the body and load jQuery plugin on to bottom of the page headjs

As I understand your issue:

  1. jQuery is not available on the page before it loads.
  2. You use templates and each has it's own js code to run when page loads
  3. You want them to run with jQuery.

If I got you right, here is the solution:

  1. In <head> define global task array:

        ...
        <script>
            const JQUERY_READY_TASKS = []
        </script>
    </head>
    
  2. After you load jQuery and other scripts define:

        ...
        <script>
            jQuery(document).ready(() => {
                // Execute all tasks added by templates
                for (let n=0; n<JQUERY_READY_TASKS.length; n++)
                    JQUERY_READY_TASKS[n](jQuery)
                }
            });
        </script>
    </body>
    
  3. Wrap initialization code of your templates in functions:

        ...
        <script>
            // Within template
            JQUERY_READY_TASKS.push(($) => {
                // Template init code
                // You can use $ as jquery here
            })
        </script>
        ...
    

Just have a page-specific $(document).ready().

Have you tried "@section script"? It will automatic add the codes at the end of the page, thus you can have page specific jQuery scripts.

@section scripts {
<script>
 jQuery(document).ready(function () {
//put your jQuery codes here
});
</script>
}
发布评论

评论列表(0)

  1. 暂无评论