Brainfeeder Brainfeeder - 1 year ago 104
Javascript Question

Prevent $.pjax from moving dynamic script tags to the head section

We implemented $.pjax in a CodeIgniter application a few months ago. And it seemed to be working perfect. Recently users started complaining that some buttons had strange behaviours sometimes. After debugging a while, we discovered that PJAX is moving script tags from the freshly loaded fragment to the head section of the document.

This is great, you would think, because title and css resources are also moved to the head. We can benefit from this (pushstate, browser tab name, ...).

Sadly, clicking another pjax link will not remove these added script/css tags. This can get strange when bindings to an element with the same id or class are present in the other newly added scripts.. It tends to break things.

Does anyone know how to remove earlier added script tags (not all, only those added by pjax)? Currently the only way out is to drop pjax.. But I love it to much :(

As the title of this question suggests, we think the easiest way might be to prevent $.pjax from moving the tags from the fragment to the head in the first place.

Answer Source

It has been a while since I asked this question. We found a workaround for this pjax behaviour.

pjax only moves 'linked' javascript and css sources. When the code is in the partial, it will stay at the same place and will be executed once the partial content is added to the DOM.

At Github some suggested to use context="inline" on the <script> tags that shouldn't be moved to the <head> section.

So our solution for scripts in partial views:

<script type="text/javascript" context="inline">
    <?= file_get_contents(js_url().'controllers/'.$jsController.'.js'); ?>

Obviously one should check if the file exists before reading it with PHP.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download