I have contactus.js in whitch is defined the sendMail(to) function.
I have main.js:
...
$('#ContactUs').click(function(){
// how to execute /contactus.js, and when done, send mail?
sendMail(to);
});
...
However, as main.js is used in every HTML page of the site, I didn't like to include contactus.js before main.js, in order do not load a useless script.
I need to load (execute) contactus.js only when a click on the #contactus was made.
EDIT:
I added a Fiddle here, to demonstrate the effect:
$(function() {
console.log("ready!");
$('#submit').click(function() {
console.log("click start");
$.getScript("http://parsleyjs.org/dist/parsley.js", function() {
console.log("the object is: " + window.parsley);
});
console.log("click end");
});
});
<form action="alert('done');" id="myForm">
<input type="email" required>
<div id="submit">submit</div>
</form>
I expect "window.parsley" be defined, but is not...
Use jQuery.getScript, like below.
Load a JavaScript file from the server using a GET HTTP request, then execute it.
$('#ContactUs').click(function(){
// how to execute /contactus.js, and when done, send mail?
$.getScript("/contactus.js", function() {
sendMail(to);
});
});
Use jQuery.getScript() like this:
$('#ContactUs').click(function(){
$.getScript('/path/to/contactus.js', function() {
sendMail(to);
});
});
I'd assume then you'd want to inject the script into the head. like:
var script = document.createElement('script');
script.src = " /contactus.js";
document.getElementsByTagName('head')[0].appendChild(script);
This can also be achieve in jquery using $.getScript (see docs here)
Having said that, if the script is only small and used for the contact form, loading it along all the html pages might be the better option.
The script would be cached, but the place where it's used (on click) would be more responsive as you wont be waiting for the script to load
May be you are looking for $.getScript.
Or add <script> tag dynamically,
$('#ContactUs').click(function(){
var src = navigator.appName == "contactus.js";
var regScript = document.createElement("script");
regScript.setAttribute("src", src);
document.getElementsByTagName("head")[0].appendChild(script);
sendMail(to);
});
Hope it helps, thanks.
Related
I request an external script by adding this to my HTML file:
<script>
$(document).on("turbolinks:load", function() {
$.getScript("https://example.com/script");
});
</script>
Say the content of the script is as follows:
doSomething = function() {
// ...
};
My website is a Ruby on Rails app with Turbolinks, which caches the content of the requested script between page visits. My script tag does not know about this, so if I revisit the page it will request the script again. How do I avoid this? My current solution is to check if the scripts content is known:
<script>
$(document).on("turbolinks:load", function() {
if (!window.doSomething) {
$.getScript("https://example.com/script");
}
});
</script>
But this depends on the content inside the script staying the same. So I would rather check if a script from the source https://example.com/script already exists? Or maybe some other approach. Any ideas?
Like epascarello commented, $.getScript appends to head so check that it's not in head before getting it.
if (!$('head script[src^="https://example.com/script"]').length){
$.getScript("https://example.com/script");
}
Use the Attribute Starts With Selector because $.getScript appends a timestamp to avoid getting an already cached version, i.e. it requests a new URL each time.
If you're going to use it more than once:
function getScriptOnce(url){
let selector = 'head script[src^="' + url + '"]';
if (!$(selector).length){
$.getScript(url);
}
}
getScriptOnce("https://example.com/script");
I have a project that uses jQuery. And I am trying to convert this script to Javascript. I had the following line on that script.
var a = $("#myImage");
I changed it to
var a = document.getElementById("myImage");
but script is not working because my page hasn't loaded yet when this happens. I have no idea how to fix this. Any help would be greatly appreciated. Thank you.
<body onload="var a = document.getElementById("myImage");">
</body>
onload="var a = document.getElementById("myImage");" runs when the content is fully loaded. When the body is completely loaded then var a = document.getElementById("myImage"); will run.
You need to execute the script once the page loads.
window.addEventListener("load", function(){
// .... Add your script here
});
You can include a listener on the document object to wait for the DOM to be loaded.
document.addEventListener('DOMContentLoaded', function(event) {
var a = document.getElementById("myImage");
})
Try using.
window.addEventListener('DOMContentLoaded', function(){
var a = document.getElementById("myImage");
//Rest code here
});
You could, for instance:
Place corresponding <script> tag before closing </body> tag.
Start doing things when document is loaded using a callback.
Personally, I prefer the 1st option much more since it works more stably according to my experience.
Help me please! Why this code not work? It does not show alert.
var jqueryScript = document.createElement('script');
jqueryScript.src =
'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
jqueryScript.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(jqueryScript);
$(function() {
$("#main").click(function() {
alert("asdasd");
});
});
Thank you in advance!
Probably because jQuery lib is not loaded as it loads asynchronously made that way, and no one can guarantee you when it will load on time, which is not that way if you load it by <script> tag, so $(function() { ... }); won't work as $ which represents $.jQuery( is not initialized yet. If you execute the script second time without reloading the page, it will work, as jQuery will be loaded from the first execution, even its made in wrong time.
I am having an Anchor link, on click of Anchor link, I am registering new JavaScript file html page.
On registering the JavaScript file dynamically, document is reloaded partially (As I see reload icon in browser for some time).
I want to call my JavaScript function once the script got registered (Obviously when reload icon get stopped in the browser). But the function MyJavaScriptFunction got called while document is still reloading.
Using setTimeOut resolves the issue but I don't want to use it as page loading time is not fixed. Please help.
The code I am using is as follow:
function addScriptDynamically(src, callback) {
var s = document.createElement('script');
s.setAttribute('src', src);
s.onload = callback;
document.body.appendChild(s);
}
addScriptDynamically('URL Of JS File',function(){
MyJavaScriptFunction();
})
What I tried so far...
Option-1:
addScriptDynamically('URL Of JS File',function(){
$(document).ready(function(){
MyJavaScriptFunction();
});
})
Option-2:
addScriptDynamically('URL Of JS File',function(){
$(window).load(function(){
MyJavaScriptFunction();
});
})
jquery has a function for this purpose.
Using jquery
$(function () {
//write your function code here.
})
This function is called only when the content of the page are first loaded.
2)
Using Javascript
window.onload = function(){
//write your function code here.
}
I have a webpage on which there a button.
On button press, I intent to embed a script in the head section of the page to enable a plugin. I can manually insert the snippet and my plugin but I want to be able to do this on button click itself to keep it as an optional element for my users.
What is the way to go about this?
As per #padde's query, the script looks like the following the way I include in my header:
<script type="text/javascript" src="http://code.abc.com/farfalla.js"></script>
<script type="text/javascript" src="http://code.abc.com/postmessage.js"></script>
Use createElement() of javascript and add it to the DOM
Check the below link for more information : http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
If you are using jquery then you can use $.getScript to load the external js file.
$.getScript('filename.js',function(){
//your code ...
});
Normally, you would simply put the script inside the <head> tags. Then, extract the initializing code from the included script and run it when the button was clicked.
Edit
You can also try this:
HTML
<button id="share-button">Share this</button>
JavaScript
dynamicCode = 'alert("script loaded");'
scriptLoaded = false;
buttonClicked = function(e) {
if( !scriptLoaded ) {
var script = document.createElement('script');
script.text = dynamicCode;
document.getElementsByTagName('head')[0].appendChild(script);
scriptLoaded = true;
}
alert("thanks for sharing");
};
button = document.getElementById('share-button');
button.onclick=buttonClicked;
where you would load the dynamicCode with an Ajax call or whatever you like. The code is only loaded once. I've put together a jsfiddle for you, so you can try it out.