jQuery: How to insert or remove a .js file at runtime? - javascript

i want to add a .js file after a link has been clicked.
The .js file is a script, that has no function to call directly, but the file has to be inserted in the body part of the site.
Another solution would be, if the file is called at page load and if the click event of the link is called, then remove the .js file.
I've tried something like this, but nothing happens:
$(".myLink").click(function(){
$.getScript("myJavascriptFile.js");
});
and also here:
$(".myLink").click(function(){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "app_javascript/dragscroll.js";
$(".myDiv").append(script); // or $("body").append(script);
});

Well, actually, "nothing happens" sounds most probably too loud.
getScript is by all means asynchronous, so you should provide any code, which relies on using this script in load handler, which is actually, the second param.
$.getScript('here_comes_the_script.js', function(){...//here comes the code})
You can use some wrapping to make thing more flexible - by passing events to load handler, something like this:
getScriptDetectable = function(src) {
getScript(src, function() {
$(document).trigger("new_script", {src: src})
});
}
But this, of course, doesn't free you from considering the fact that this code is asynchronous.
And about removing script. There is actually no general way to make browser "unsee" the code.
You can try do something like:
var src = document.querySelector('script');
src.parentNode.removeChild(src);
but all code in this file which has been evaluated already is evaluated, so there is no much sense in this.

There is jQuery function for that - jQuery.getScript(). It appends the script tag to the body, so it does exactly what you want.
I do not think removing this tag will disable the code - you would need to separately delete all the defined global functions, unbind the event handlers etc.

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

Design a header script to run after the document is finished loading

I have a javascript function, "loadFramework()" that modifies an HTML document. Specifically, it repeatedly runs the jQuery command $("#element-id").load("document/name.html"), which injects the HTML in document/name.html directly into the element with #element-id.
Originally, I ran loadFramework() in a script in the document's header. However, since then I've realized that the function fails if the page has not loaded yet, since it relies on there being an element with #element-id.
I can't figure out how to get this function to run when it should. A simple solution seemed to be setting it to be the document.onload function:
document.onload = function() {
loadFramework();
}
But in this case it never seems to run at all.
How do I make sure a header function runs only after the document has loaded?
You should use window.onload if you are looking for a vanilla JS option
window.onload = function() {
loadFramework();
}
Jquery load takes additional argument "complete". You can run the javascript there. So the code would be:
$("#element-id").load("document/name.html", function(){
loadFramework();
});
You can also use $(document).ready(function{loadFramework()}) inside the html you are loading.
If you want to execute the loadFramework() method after "document/name.html" is loaded, I would suggest the following code.
$(function() {
$("#element-id").load("document/name.html", function(){
loadFramework();
});
});

Reload? Javascript after Jquery .live/.load

I wanted to load some fragments of external content inside a div, through a menu.
Found "load" and "live", found a tutorial used it = success!
Except, like what's explicit in the documentation, it doesn't load JavaScript.
The thing is, the destination page already loads, inside the header, that same JavaScript, 'cause Wordpress loads it in every page. In this particular page, I'm only using the plugin (nextgen gallery) through the jQuery AJAX call.
So, what I believe is my problem is that I somehow need to alert/reload the JavaScript, right?
And how can I do this?
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
// ajax pagination
jQuery('#naveg a').live('click', function(){ // if not using wp-page-numbers, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('#fora').html('<div class="loading"><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('#fora').load(link+' #dentro')
return false;
});
}); // end ready function
</script>
PS: I've substituted "live" with "on" but didn't work either.
I'm not sure if I understand... your load() command is puling in some Javascript that you want executed? I'm not sure if you can do that. But if you just need to call some JS upon load() completion, you can pass it a function like so:
jQuery('#fora').load(link+' #dentro', function() {
console.log("load completed");
// JS code to be executed...
});
If you want to execute Javascript code included in the loaded page (the page you retrieve via .load()), than you have to use the url-parameter without the "suffixed selector expression". See jQuery documentation for (.load()):
Note: When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is however called with a selector expression appended to the
URL, the scripts are stripped out prior to the DOM being updated,
which is why they are never executed. An example of both cases can be
seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
However in this case, script blocks in the document being loaded into
#b are stripped out prior to being executed:
$('#b').load('article.html #target');
I think that's your problem (although I have no solution for you, sorry).
Proposal: Maybe you can load the whole page (including the Scripts) and remove (or hide) the parts you don't need?
Cheers.

How to know if resource file is loaded by the page in Javascript

How can I to know if resource file is loaded by a page using Javascript?
For example some .css, js or other sort of sort of file?
It depends on whether you're adding the files dynamically. I'll explain for JavaScript files.
Either use this piece of code to load an external file:
var scriptElem = document.createElement('script');
scriptElem.onload = function() {alert('Script loaded.');}
scriptElem.src = 'test.js';
document.getElementsByTagName('head')[0].appendChild(scriptElem);
Or if you're adding them through HTML, you can make the script file reflect the fact it's been loaded with a variable. E.g. in test.js:
// ...rest of file...
window.testLoaded = true;
You can then check for window.testLoaded === true anywhere on the page.
For CSS files you can also use the first technique, but of course not the second. It might be possible to define a stub definition for a class .test, then create an element with that class and check whether it has a certain style that you set in the CSS file.
Use jQuery.ready event which means that all the page has been setup and then you start executing your JavaScript logic
$(document).ready(function(){
//your code
});
If you have the need to load stuff asynchronously then you should use your JavaScript code to load it like the example of loading a script:
$.getScript("http://.../some.js", function(){
//script loaded and hooked on the page; your custom logic here
});
For anything more complex I'd suggest some dependency management system like requireJS.

Removing jQuery ajax-added js-files from document again?

My site operates on an ajax "framework". Whenever a user opens a new page, that page loads in the necessary css and js files to view the page properly and adds them to the current document. The js files are loaded like this in jQuery:
function getJS(jsfiles) {
$.each(jsfiles, function(i, val) {
$.getScript(val);
});
}
My problem is that whenever a js-file is loaded, that file is added to the document permanently and operates across all ajax "sub-sites". Therefore I get problems with reserved function names, functions that requires certain DOM-elements to be present when executed and throws an error otherwise, etc. etc. Is there a way to remove these files from the document again?
I don't know how jQuery attaches new scripts, but you could do an AJAX request and build your own script elements in the callback, giving them a class that can be selected later for removal.
$.ajax({
url:'test.js',
dataType: 'text',
success: function(script) {
var head = document.getElementsByTagName('head')[0];
var scr_elem = document.createElement('script');
scr_elem.setAttribute("class","new_script");
scr_elem.setAttribute("className","new_script");
scr_elem.type="text/javascript";
scr_elem.appendChild(document.createTextNode(script));
head.appendChild(scr_elem);
}
});
// Later on
$('.new_script').remove();
Note that I've only tested this in Webkit and Firefox.
You could scope the contents of the JavaScript files you are loading, using a self-executing function. Or try assigning an ID to the script-blocks and remove them by doing: $("id of the script block").remove();.
You can try to do something like this
$('head').empty();
$('head').append('<script src="yourscript.js" type="text/javascript" />');
Hope this helps

Categories

Resources