Given a typical script tag:
<script src="foo.com/myscript.js"></script>
would it be possible to directly read the contents of myscript.js as a string or something?
For example:
<script id="myscript" src="foo.com/myscript.js"></script>
<script>
var inners = document.getElementById("myscript").//raw contents of myscript.js
</script>
No. You can read the contents of the inline script tag, because it actually does have content:
<script id="myscript">
var inners = document.getElementById("myscript").textContent;
</script>
But for the external JS, the script contents are not actually put into the DOM; you would need to re-fetch it using AJAX (it would normally be cached unless anti-caching measures were taken, so you would not really take much time to re-fetch).
Related
I have a script (Google Maps, to be exact) that is loading dynamically, and for a couple of reasons, I cannot alter how this initially loads by default.
Through JavaScript, I would like to find the string libraries=places and change it to libraries=places,visualization after the fact
So, the originally output:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=places">
</script>
Would be:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=places,visualization">
</script>
Is this even possible?
Thanks In Advance
this solution should apply to yours as well:
How do I include a JavaScript file in another JavaScript file?
script.src = url; will be the line where you add the src url however you like
First of all Give the google map script tag an ID:
<script id="google_map_script" type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
Then do:
var google_map_script = document.getElementById("google_map_script")
google_map_script.setAttribute("src", "https://maps.googleapis.com/maps/api/js?libraries=places,visualization")
Edit: since apparently this isn't what is needed then what about this:
var script = document.createElement('script');
my_awesome_script.setAttribute('src','https://maps.googleapis.com/maps/api/js?libraries=places,visualization');
document.head.appendChild(script);
Also have a look into using postscribe.
Actually I was trying to get the concept of the module pattern. Here I have simple code which I used to type directly on the page. It was fine until I tried to separate the actual code from the HTML file and kept only a single line of code on the main HTML file:
<body>
<script type='text/javascript' src='module.js'>
// module.JS file was here ....
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
</body>
File module.JS
var module = (function() {
return {
show:function(keyCode){
document.body.innerHTML+=(String.fromCharCode(keyCode));
}
};
})();
You'll need to have two <script> elements for this.
Use one to "import" your external module and another for the script you want to embed directly on the page:
<script type='text/javascript' src='module.js'></script>
<script type='text/javascript'>
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
For more information, you can check out this MDN documentation page. Here is an excerpt talking about the src attribute (emphasis added):
This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. Script elements with an src attribute specified should not have a script embedded within its tags.
A script block referring to an external JavaScript source should be separate and any script inside of it does not get executed. So you need two separate script blocks one for the external JavaScript file and the other for your script.
<script src='module.js'></script>
<script>
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
I am adding some third party code to my page. This is the code sample they supply which works:
<script type="text/javascript">
document.write(unescape("%3Cscript src='//munchkin.marketo.net/munchkin.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script>
Munchkin.init('123-ABC-456');
</script>
I thought I would remove some tags and turned it into this:
<script type="text/javascript">
document.write(unescape("%3Cscript src='//munchkin.marketo.net/munchkin.js' type='text/javascript'%3E%3C/script%3E"));
Munchkin.init('381-KZC-440');
</script>
This now doesn't work, stating that Munchkin is not defined. I did a look around and read about scope but I'm still confused as to why it breaks, the order has been kept the same. If I had to guess I would say that the JS file being called is allowed to load completely before the page continues onto the next script tag, whereas in my version it continues too quickly. If so, this could presumably be used for many advantages as it's essentially an "onloadcomplete" event?
The new script won't be loaded until the current script block terminates. Think about it like this: The first code will result in a DOM structure like:
<script type="text/javascript">
document.write(...;
</script>
<script src='//munchkin.marketo.net/munchkin.js'></script>
<script>
Munchkin.init('123-ABC-456');
</script>
As you can see, the script is inserted after the script that calls document.write. Therefore the script is loaded when the third script element is evaluated.
But if you have
<script type="text/javascript">
document.write(...);
Munchkin.init('123-ABC-456');
</script>
<script src='//munchkin.marketo.net/munchkin.js'></script>
then you are trying to access the object before the script was loaded.
So when I want to put a Google +1 button on webpages, I would do this:
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{lang: 'zh-TW'}
</script>
But I am wondering, there is an object in the script tag, but it is also loading plusone.js! At the end the script can also get the object inside the tag. How does Google do that? Unlike normally I would not put anything inside. Normally I would do
<script type"text/javascript" src="script.js"></script>
Since the URL is known, it's simple enough:
JSON.parse(
document.querySelector("script[src='https://apis.google.com/js/plusone.js']")
.innerHTML.replace(/^\s+|\s+$/g,'')
);
That said, as Alohci pointed out in the comments, the last script on the page will be the last one loaded when the script runs, because (unless specified otherwise) scripts are blocking. Therefore, this would work:
var scripts = document.getElementsByTagName('script');
var data = JSON.parse(scripts[scripts.length-1].innerHTML.replace(/^\s+|\s+$/g,''));
I have some javascript which will create some sort of widget on a page. I will be giving this snippet to clients so I want them to have to do very little.
The most obvious solution which I have work right now looks something like this:
<div id="divContent"></div>
<script type="text/javascript">
MakeWidget('divContent');
</script>
Make widget basically looks for the divContent div and fill it with my widget's html.
Is there a better way to do this?
Can you replace a Script Tag with a Div using Javascript in that Script Tag?
I would really like it if I could reduce the code down to only the MakeWidget function and it would replace itself and the script tag with the html the function generates.
Edit - I essentially want to generate HTML exactly where the MakeWidget function is called on the page.
Can you replace a Script Tag with a Div using Javascript in that Script Tag?
Yes. When the <script> element is reached, assuming it is not a defer or async script, it will be the last script element in the page so far. So you can say, either inline or in an external script:
<script type="text/javascript">
(function() {
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
var div= document.createElement('div');
div.innerHTML= 'Whatever content is going to be inserted';
script.parentNode.insertBefore(div, script);
})();
</script>
You have to have MakeWidget defined somewhere, right? Presumably this is going to be in an external script. Why not just have the external script source just attach itself to the divContent using the window.onload method?
This would result in this code on your client's page:
<script src="http://foo.com/makewidget.js"></script>
Your makewidget.js code could then look like this:
window.onload = function() { MakeWidget('divContent') }
There may some issues with other scripts loading and probably some cross-browser compatibility issues but that should get you pointed in the right direction.
So you want to have a script element which replaces itself with div.
Your initial code is like this:
<div id="divContent"></div>
<script>
MakeWidget('divContent');
</script>
You can rewrite it like this (I am using JQuery):
<script id="scriptContent">
$('#scriptContent').after('<div id="divContent"></div>');
MakeWidget('divContent');
$('#scriptContent').remove();
</script>
I have not tried it though!
I would think it would be possible to do it as follows:
<div id="divWidgets">
<script type="text/javascript">
MakeWidgets("divWidgets");
</script>
</div>
The end result should be (if I understand your description correctly) that MakeWidgets will replace the contents of the DIV, which, in this case, is the script itself.