简体   繁体   中英

How to include a javascript file after another loads?

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?

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 !

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> 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM