Motive
Motive

Reputation: 3111

Where to put JS that is used in only one view in Codeigniter

I'm working on a Codeigniter application and I use a template system to build my views.

During development, I have just been including my jQuery into the actual view itself. The problem with this is that it ends up in the body of the page. I'd prefer to have it at the footer.

Most of the jQuery is only used once in a specific view, so I don't see the sense of putting it all into the footer partial.

What are my options?

Upvotes: 0

Views: 70

Answers (2)

Rooneyl
Rooneyl

Reputation: 7902

The template library by Williams Concepts has a method for you to add JavaScript on an adhoc basis.

You can then add the JavaScript in the method being called, something like;

$this->template->add_js($script, $type = 'import', $defer = FALSE)

Upvotes: 1

jcolebrand
jcolebrand

Reputation: 16025

During development, I have just been including my jQuery into the actual view itself. The problem with this is that it ends up in the body of the page. I'd prefer to have it at the footer.

So move the jQuery inclusion to the footer? Means that you'll have to load the other scripts after this, which doesn't work so well with templates :-\ If you only need to load jQuery in some places, see below.

Most of the jQuery is only used once in a specific view, so I don't see the sense of putting it all into the footer partial.

So put it just into the view. <script> is a tag just like anything else. Include it just when you need it. If you might be loading this partial repeatedly, test it like so: <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.7.2.min.js"><\/script>')</script> and it should insert into the page for you if it hasn't yet been loaded, and if it has, it skips the insertion. That way you have a sort of just-in-time jQuery loading pattern.

Upvotes: 0

Related Questions