0

I have an iframe with id="iframe" Inside my footer of index.php, I want to include a javascript file after the iframe loads.

So far I have:

<script>
$('#iframe').onload = function () {
    </script>
        <script src="/js/myjsfile.js"></script>
    <script>
}
</script>

However, the webpage is getting angry and saying: SyntaxError: Unexpected end of input (for the {) and SyntaxError: Unexpected token } How can I include these files after load of another?

Rolando Corratge Nieves
  • 1,233
  • 2
  • 10
  • 25
George Chen
  • 89
  • 1
  • 9

3 Answers3

1

You should try this :

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);

See this post for more information.

Hope this will help !

  • How would I append this if I'm trying to do this inside of the footer.php file? – George Chen Jul 28 '17 at 17:05
  • It works the same, no matter if the script is inside the header.php or the footer.php. If you put this into jQuery('#iframe').ready tag, script will be loaded after your iframe will be ready too. – Vianney Ain Jul 28 '17 at 17:08
0

You can use jQuery.getScript() and detect the load event for the iframe.

$('#iframe').on('load', function(e) {
    $.getScript('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js', function() {
        // library is loaded. Now I can start to use.;
        console.log('Now the library is loaded!');
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<iframe id="iframe" src="https://dummyimage.com/200x200/000/fff" style="width: 200px;height: 200px"></iframe>

A different approach can be based on adding the script element dynamically like in:

$('#iframe').on('load', function(e) {
  $('head').append($('<script/>', {src: 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js'}));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<iframe id="iframe" src="https://dummyimage.com/600x400/000/fff" style="width: 200px;height: 200px"></iframe>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
-1

You can inject a script tag on iframe load like this.

        <script>
         $('#iframe').on('load', function() {
             var script = document.createElement('script');
             script.src = '/js/myjsfile.js';
             document.body.appendChild(script);
         });
        </script>
Truextacy
  • 562
  • 1
  • 5
  • 26