Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

cordova - Executing several JS files with Ratchet push.js library

I′m developing a Phonegap app with Ratchet 2.0.2 using push.js for transition between pages. Everything is working smoothly but a couple of hours ago I stumble upon this:

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.

After doing more research I found out this: Execute custom script after page loaded with RatchetPush.js

Which is almost the same problem I have, however I need to go further because I need to load not only one script, but two (and perhaps more in the future), how can I take advantage of checkPage() to load more than one script?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE: Also see this question.

Here is a solution that I have tried and it seems to work correctly, but I'm looking for some feedback on if this is the best method or not... please feel free to comment, and I will make updates as needed. I know that eval() is dangerous, but I' not sure how dangerous it is in this case.

On your indexfirst page place the following script at the bottom of your page, OUTSIDE of the .content div, so that it does not get overwritten by push.js.

<script>
    window.addEventListener('push', function(){
        var scriptsList = document.querySelectorAll('script.js-custom');
        for(var i = 0; i < scriptsList.length; ++i) {
            eval(scriptsList[i].innerHTML);
        }
    });
</script>

Then, on any other page that gets loaded via push.js, just give the script a class of .js-custom. This script must be placed INSIDE the .content div.

<div class="content">
    ...
    <script class="js-custom">
         alert('I was executed!');
    </script>
</div>

The fist script will find and loop through any <script> tags with the .js-custom class and execute it's contents using eval().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...