|
When using jQuery, it’s almost a given that you are using the base.html - items.html (inherits base.html) - mealplans.html (inherits base.html) And then in each of those: - items.html
{% block js_ready %}
massive amount of javascript,
(especially since my latest site,
fridgeclick.com has a lot of ajax)
{% endblock %}
- mealplans.html ( the same here )
However modularized I thought this was, when I did a “view source” in the browser after navigating to either of these pages, there was a big mess, way too much javascript looking back at me.
The right way to do it ( or at least much better.)Take one of your bottom-level template pages, somepage.html ( any of your content pages which inherits from the base.html ) 1. Remove all of the individual js statements that you previously had, outside of a function, but in a tag block ( of which I called mine: js_ready ). I I had stuff inside my items.html file such as:
{% block js_ready %}
$(".categorybox").change(function() {
$('#ingred_table tbody tr').hide();
...
}
...
(many, many other event-binding functions or other
stuff that needs to be executed upon page-load)
{% endblock %}
2. Put all of these in a brand new external js file, in this case somepage.js, however place all of them inside functions. Obviously, yes, if you want you could pile all of the statements into a single function and call it: function ToLoadOnPageReady(), or something. However, it’s just better to create several that categorize the type of document.ready functions that you have. For instance, I have a function called bind_filter_handlers, a bunch of jquery javascript that handles what happens when using two different Select boxes. I have another one that is called misc_init(), which initializes simple booleans, and an object literal var that sends ajax data. 3. In your somepage.html file, add this:
{% block extern_js %}
<script type="text/javascript" src="{{MEDIA_URL}}js/somepage.js"</script>
{% endblock %}
Obviously, the purpose for this above is to add this “extern_js” tag to the base.html. 4. Again in your somepage.html file, inside a block of course , call these functions (obviously not these exact ones): {% block js_ready %} After these, you have this: Hope this was all somewhat clear. Post a comment
|