[英]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. 我在index.php的页脚中有一个id =“ iframe”的iframe,在iframe加载后,我想包含一个javascript文件。
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? 但是,该网页很生气,并说:SyntaxError:意外的输入结尾(对于{)和SyntaxError:意外的标记}如何在加载另一个文件之后包括这些文件?
You can use jQuery.getScript() and detect the load event for the iframe. 您可以使用jQuery.getScript()并检测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. 您可以像这样在iframe负载上注入脚本代码。
<script>
$('#iframe').on('load', function() {
var script = document.createElement('script');
script.src = '/js/myjsfile.js';
document.body.appendChild(script);
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.