Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute custom script after page loaded with Ratchet\Push.js

So on the GitHub documentation for Ratchet 2.0.2 I found the following statement.

Script tags containing JavaScript will not be executed on pages that are loaded with push.js. If you would like to attach event handlers to elements on other pages, document-level event delegation is a common solution.

Can someone please spell out exactly how to get a custom <script> to execute after being loaded by Push.js?

On my first page, I have a Table view, with several links to other pages, one of them being a link to a second page with a Twitter Feed widget on it.

<li class="table-view-cell media">
    <a class="navigate-right" href="Twitter.php" data-transition="slide-in">
        <span class="media-object pull-left icon icon-person"></span>
        <div class="media-body">
            Twitter Feed
        </div>
    </a>
</li>

The second page only contains the twitter feed widget code. When I browse to this page directly (without being loaded by Push.js) everything loads correctly, but when it is loaded via Push.js, the script is not executed.

Can someone please explain what I need to do to get this script to execute after being loaded by Push.js? I've searched Google, Stack Exchange, and Github\Ratchet issues and have not been able to find a good example of how to accomplish this.

One solution would be to add data-ignore="push" to the link, but I want to know how to do with WITH push.js.

<div class="content">
    <a class="twitter-timeline" href="https://twitter.com/XXXX" data-widget-id="XXXX">Tweets by XXX</a>
</div>
<script>
    !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>
like image 760
Schmalzy Avatar asked Apr 17 '14 23:04

Schmalzy


1 Answers

EDIT: below was how I originally solved this problem, which worked fine, but I came up with a better solution, which I posted as the answer to this question.


I finally figured it out.

On your first page, you need to do the following...

var checkPage = function(){
    //Only run if twitter-widget exists on page
    if(document.getElementById('twitter-widget')) {
        loadTwitterFeed(document,"script","twitter-wjs");
    }
};

window.addEventListener('push', checkPage);

checkPage() will execute for every time a new page is loaded via push.

like image 169
Schmalzy Avatar answered Oct 20 '22 07:10

Schmalzy