Strudel
Strudel

Reputation: 819

using jQuery (put at the bottom of the page) on specific page

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.

Upvotes: 3

Views: 10315

Answers (8)

Strudel
Strudel

Reputation: 819

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

Upvotes: 2

Lex Podgorny
Lex Podgorny

Reputation: 2930

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>
        ...
    

Upvotes: 1

David Porter
David Porter

Reputation: 21

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>

Upvotes: 2

CapLockAlt
CapLockAlt

Reputation: 9

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>
}

Upvotes: 0

Justin Johnson
Justin Johnson

Reputation: 31300

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.

Upvotes: 4

Russ Cam
Russ Cam

Reputation: 125508

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();

Upvotes: 3

kaba
kaba

Reputation: 405

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.

Upvotes: 3

slikts
slikts

Reputation: 8158

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

Upvotes: 0

Related Questions