Reputation: 850
I have some jQuery code on each page of my application. I want to compress and put them all together in one file. Is it possible to load the jQuery only on a certain div load ? I tried adding a DIV id inside the body(ID=addProject) with the following jQuery code:
$("#addProject").ready(function() {
alert("test");
});
$("#addProject").pageload(function() {
alert("test");
});
$("#addProject").on('pageload',function() {
alert("test");
});
Upvotes: 3
Views: 923
Reputation: 7149
Yes you can. You can test whether the element exists when the page finishes loading.
$(document).ready(function () {
// Page 1
if ($('#page-1').length > 0) {
// Do specific stuff for page 1
}
// Page 2
if ($('#page-2').length > 0) { }
// Etc...
});
However, you're probably better off wrapping your code in view models that you then call on the page. Why? Well, maybe you (accidentally) create an element on another page with the same class or id and suddenly your JavaScript is executed on a page where it shouldn't be. Or what if you (or someone else) updates the website template and changes classes or ids on elements? Now your code stops working...
You could have one JS file (or many) with view models, like this:
var Page1ViewModel = function () {
// All JS code specific to Page 1
};
var Page2ViewModel = function () {
// All JS code specific to Page 2
};
And on your page you call the relevant view model:
<script type="text/javascript">
var viewModel;
$(document).ready(function () {
viewModel = new Page1ViewModel();
});
</script>
These are just two out of many possible solutions.
Upvotes: 3
Reputation: 2143
You can just wait till the doc is ready, then search for each element.
$(function() {
if ($("#addProject").length > 0) {
// execute some code for addProject
}
if ($("#deleteProject").length > 0) {
// execute some code for deleteProject
}
});
However it should be noted that if you're just trying to bind actions to elements in those divs (for example .on("click")
events) then you can just go ahead and attempt to bind those even if the elements don't exist. It won't throw errors or anything. It just causes a minor performance hit depending on the size of the document.
Upvotes: 4
Reputation: 78545
You need to test for the existence of #addProject:
// Wait for the document to become ready
$(function() {
// This will return the number of elements which match the selector. If this
// is true, then the element exists
if($("#addProject").length) {
alert("here");
// Put your addProject only scripts here
}
});
Upvotes: 2