我如何从脚本标记中读取JS作为数据? [英] How do I read JS as data from a script tag?

查看:123
本文介绍了我如何从脚本标记中读取JS作为数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个外部文件(比方说foo.js)

 函数baz(){} 

然后在我的HTML中,使用脚本标记导入它:

 < script type =text / javascriptsrc =foo.js>< / script> 

我希望能够从脚本标记中获取JS的字符串。我尝试过jquery的html()和innerHTML和innerText属性,但它们都返回空字符串。注意:我试图避免使用AJAX,因为我的服务器是缓慢,并减少网页的大小,即使有缓存。



编辑:
我想要得到的字符串将包含JavaScript文件中的数据,而不是它的URL:

  getJsData(document.querySelector('script [src =foo.js]'))= ='function baz(){}'


解决方案

不完全明白它是什么以及你为什么要实现这一点。考虑到由于缓慢的服务器问题你不想使用 ajax ,所以你最好还是老派。
如果你的页面不是很重,你可以 -




  • 隐藏隐藏 iframe 将其src指向您的JS文件。


  • 等待iframe中调用 $('document')。ready() ,即让iFrame加载所有内容。

  • 复制载入的iframe的内容到您想要的HTML元素容器中。




希望这有助于您!

I have a external file (let's say foo.js)

function baz() {} 

Then in my HTML, I import it with the script tag:

<script type="text/javascript" src="foo.js"></script>

I want to be able to get a string of the JS from inside of the script tag. I have tried jquery's html(), and the innerHTML and innerText attributes, but they all return empty strings.

Note: I am trying to avoid AJAX, because my server is slow, and to decrease the size of the webpage, even with caches.

Edit: The string I want to get would contain the data in the javascript file, not its URL:

getJsData(document.querySelector('script[src="foo.js"]')) == 'function baz() {}'

解决方案

I may not exactly understand what is it and why you want to implement this. Considering that you do not want to use ajax due to slow server issues, you might as well do it old school. If your page is not very heavy, you can -

  • Put a hidden iframe on the page pointing its src to your JS file.

  • Wait for the $('document').ready() to be called inside the iframe, i.e. let the iFrame load all the content.

  • Copy the contents of the iframe one its loaded into the HTML element container you want.

Hope this helps!

这篇关于我如何从脚本标记中读取JS作为数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆