Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read JS as data from a script tag?

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() {}'
like image 871
mailmindlin Avatar asked Jul 04 '14 04:07

mailmindlin


1 Answers

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!

like image 171
Swanidhi Avatar answered Oct 13 '22 01:10

Swanidhi