I added js code dynamically:
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.id ="jsChange";
js.src = "myRoute.js";
head.appendChild(js);
It works fine, the problem is when I try to remove, I can get the way.
$('#jsChange').remove() //Doesnt work
I also try to add a div in head and put the js inside:
$('#divToJS').append(js);
and:
$('#divToJS').empty(); // doesnt work
How can I do it?
Your empty and remove both need () on the call.
E.G.
$('#jsChange').remove to $('#jsChange').remove();
$('#divToJS').empty to $('#divToJS').empty();
Unless i've misread the question, this should solve your issue.
Related
I want to add a element into the existing DOM to have the javascript code run.
I did this with YUI:
var scriptNode = Y.Node.create('<script type="text/javascript" charset="utf-8">alert("Hello world!");<\/script>');
var headNode = Y.one('head');
headNode.append(scriptNode);
It's successfully added to the DOM but it doesn't give me an alert.
Someone knows what the problem is?
I have no idea how YUI's Node.create() function works, so no comment on that. But a simple cross-browser script is:
window.onload = function() {
var s = document.createElement('script');
s.type = 'text/javascript';
var code = 'alert("hello world!");';
try {
s.appendChild(document.createTextNode(code));
document.body.appendChild(s);
} catch (e) {
s.text = code;
document.body.appendChild(s);
}
}
The try..catch block is necessary as most browsers like the first method but some don't and throw an error. The second method covers those. You can also simply eval the code, which is more or less equivalent and what some libraries do.
I found this function in the JQuery source, which seems to do what you want and feels a bit cleaner than the other approaches to me. But then again I am a JS beginner and probably don't see the details. Anyways, somebody might take something useful away from this.
function DOMEval( code, doc ) {
doc = doc || document;
var script = doc.createElement( "script" );
script.text = code;
doc.head.appendChild( script ).parentNode.removeChild( script );
}
I am trying to load a js script dynamically in index.html file using appendChild DOM method. And I am trying to use some functions from that dynamically loaded js in next line itself but I am getting error that the specified function is undefined. I understand that this error is because of async behavior of loading scripts in browser. I also used async flag as false but no use. Below are sample code.
<script>
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.async = false;
js.src = "https://example.com/test.js"; // There are two variants of test.js is there. Will be changing it dynamically based on conditional check.
head.appendChild(js);
</script>
<script>
test(); // Method inside test.js
</script>
I want test.js to be loaded immediately after executing appendChild code part. Please help me on this. Please suggest if there is any other way for my purpose.
Synchronized XHRs are deprecated. You need to add an event listener so you can call your code as soon as the script is loaded. Example below:
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
head.appendChild(js);
js.onload = function() {
console.log("yes", window.$)
};
js.src = "//code.jquery.com/jquery-3.3.1.min.js";
console.log("nope", window.$)
I need a JS statement that determine which JavaScript file to use.
I have one file:
<script type="text/javascript" src="js/jquery_computer.js"></script>
But when the screen width is less than 500px, I want load another file instead:
<script type="text/javascript" src="js/mobile_version.js"></script>
I have tried everything and it is not working.
You'd have to create that markup yourself in JS. Something like this:
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
if (screen.width > 500)
{
js.src = "js/jquery_computer.js";
}
else
{
js.src = "js/mobile_version.js";
}
head.appendChild(js);
If you want the script loaded asynchronously, the other answers here do that.
If you want it loaded synchronously with page load, this is one of the very, very few remaining valid uses cases for document.write:
<script>
(function() { // Scoping function to avoid globals
var src = /*you want the main version*/ ? "jquery_computer.js" : "mobile_version.js";
document.write('<script src="js/' + src + '"><\/script>');
})();
</script>
(I've removed type because JavaScript is the default, specifying it isn't useful.)
Maybe you can use matchMedia.js and can load a script using jQuery.getScript
$(function(){
if (matchMedia('only screen and (max-width: 500px)').matches) {
$.getScript(...);
}
});
Best would be to use built-in matchMedia API.
var script = document.createElement('script');
script.type='text/javascript';
if(window.matchMedia("(min-width:500px)").matches) {
script.src = 'js/jquery.slitslider.js';
}else{
script.src = 'js/mobile_version.js';
}
document.getElementsByTagName('head')[0].appendChild(script);
Drawback is that it is not supported in IE < 10
You don't need jQuery for this, it suffices to create the <script> tag in the DOM dynamically:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
if (<screen-width less than 500>)
script.src = "js/mobile_version.js";
else
script.src = "js/jquery_computer.js";
head.appendChild(script);
$(function(){
var width = $(document).width(),
mobile = 500;
if (width > mobile) {
$('head').append('<script class="desktop" type="text/javascript" src="js/jquery_computer.js"></script>');
$('head').find('.mobile').remove();
}
else
{
$('head').append('<script class="mobile" type="text/javascript" src="js/mobile_version.js"></script>');
$('head').find('.desktop').remove();
}
});
just use if else to detect condition and use class on script element
may be it help
You could use the async import() if you like.
import(condition ? 'js/desktop_version.js' : 'js/mobile_version.js')
In a script tag with <script type="module"> or inside a module loaded with import() from a regular <script> you can also use top-level await in the newest (experimental) browsers
<script type="module">
await import(condition ? 'js/desktop_version.js' : 'js/mobile_version.js')
</script>
But it won't work for every script.
A common reason why is those UMD module bundler that adds a closure (function(global){...}(this)) since this is undefined in modules.
Third party scripts needs to have CORS enable to load
Won't work in IE, but it's dead anyway
See other known differences
you can use $.getScript in jQuery
see here for details
I don't get some of the syntax in this block of code taken from the facebook developers site.
Are the first variables 'js' and 'id' bound in some way? What exactly is being returned in the first if statement?
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
This is the link to the page: http://developers.facebook.com/docs/guides/web/#personalization
What do you mean by "bound"?
They're function-local; js is a variable set in the 3rd and 4th lines, id is set to a string immediately.
The function itself is executed immediately after definition, with d set to document inside the function.
Nothing is returned by the first (and only explicit) return statement. And if this is the only code, a return value would be meaningless, because nothing captures the return value.
Nothing exiting here, just stolen whitespaces :)
(function(d){
var js, // variable (empty)
id = 'facebook-jssdk'; // variable with string 'facebook-jssdk'
if (d.getElementById(id)) { // is there an element with id 'facebook-jssdk'
return; // yes, so we have nothing to do and get out of here
}
js = d.createElement('script'); // create 'script' element
js.id = id; // assign id 'facebook-jssdk'
js.async = true; // load in "background" (if supported)
js.src = "//connect.facebook.net/en_US/all.js"; // set source (with the appropriate protocol; https if called via https, http otherwise)
d.getElementByTagNam('head')[0].appendChild(js); // append to first head element on page
}(document)) // immediately call the anonymous function and hand in the 'document'
Is it possible to set the contents of a script element with jQuery? Currently I have:
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescri...";
$("head").append(s);
});
What if I wanted to replace src property with actual javascript code? Is this possible with jQuery or Javascript?
There's a better way to write that, using $.getScript:
$.getScript("http://somedomain.com/somescri...")
As mentioned, you're looking for eval
eval('x = 2');
alert(x)