如何动态添加 Javascript 函数(并调用)
基于页面上的单击事件,通过 ajax 我获取一段 html 和脚本,我能够获取 script 元素并将其附加到 head 元素,但是基于 WebKit 的浏览器不会将其视为脚本(即,我无法调用附加脚本中声明的函数)。
使用 Chrome 开发人员工具,我可以看到我的脚本节点确实在那里,但它的显示方式与未动态添加的脚本块不同,非动态脚本有一个文本子元素,我无法找到复制的方法这适用于动态脚本。
有什么想法或更好的方法来做到这一点吗?驱动力是可能有大量的 html 和脚本永远不会被需要,除非用户单击特定选项卡,在这种情况下将加载相关内容(和脚本)。谢谢!
Based on a click event on the page, via ajax I fetch a block of html and script, I am able to take the script element and append it to the head element, however WebKit based browsers are not treating it as script (ie. I cannot invoke a function declared in the appended script).
Using the Chrome Developer Tools I can see that my script node is indeed there, but it shows up differently then a script block that is not added dynamically, a non-dynamic script has a text child element and I cannot figure out a way to duplicate this for the dynamic script.
Any ideas or better ways to be doing this? The driving force is there is potentially a lot of html and script that would never be needed unless a user clicks on a particular tab, in which case the relevant content (and script) would be loaded. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试使用 jQuery...它提供了一个名为 .getScript 的方法,该方法将加载JavaScript 以正确的方式动态地进行。它在所有知名浏览器中都能正常工作。
You could try using jQuery... it provides a method called .getScript that will load the JavaScript dynamically in the proper way. And it works fine in all well known browsers.
对从服务器收到的内容调用
eval()
怎么样?当然,你必须剪掉和
部分。
How about calling
eval()
on the content you receive from the server? Of course, you have to cut off the<script>
and</script>
parts.如果您使用像 jQuery 这样的库,只需使用内置方法即可完成此操作。
否则,您需要将其附加到文档而不是像这样的头部:
老实说,我不知道为什么脚本标签被这样剪切,但是很多示例都是这样做的,所以可能有一个很好的理由。
您还需要考虑到加载脚本可能需要相当长的时间,因此将其附加到正文后,您应该设置一个计时器来检查脚本是否已加载。这可以通过对脚本导出的任何全局变量进行简单的 typeof 检查来实现。
或者你可以在实际的 javascript 主体上执行 eval() ,但可能有一些警告。
但一般来说,我会将此类事情留给浏览器缓存,然后将 javascript 加载到选项卡所在的页面上。只是尽量不要使用任何 onload 事件,而是在显示选项卡时调用您需要的任何初始化程序。
If you're using a library like jQuery just use the built-in methods for doing this.
Otherwise you'd need to append it to the document rather than the head like this:
In all honesty, I have no idea why the script tag is cut like that, but a lot of examples do that so there's probably a good reason.
You'll also need to account for the fact that loading the script might take quite a while, so after you've appended this to the body you should set up a timer that checks if the script is loaded. This can be achieved with a simple typeof check on any global variable the script exports.
Or you could just do an eval() on the actual javascript body, but there might be some caveats.
Generally speaking though, I'd leave this kind of thing up to the browser cache and just load the javascript on the page that your tabs are on. Just try not to use any onload events, but rather call whatever initializers you need when the tab is displayed.