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.
Related
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.
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'm working to modify some content which is dynamically loaded via another script(let's call is script #1) onto my site. Script #1 loads some markup and content and I've been using the setTimeout() function to call my script (Script #2) using a delay of a few seconds, in order to wait to be sure that Script #1 has executed and the content is present in the DOM.
My issue is that Script#1 has different loading times, based on the server load and can be slow or fast depending on these factors, and right now, playing it safe with setTimeout() I'm often left with a second or two where my scripts are still waiting to be fired and Script #1 has already loaded the content.
How can I execute my script as soon as Script#1 successfully loads it's dynamic content?
I've found this post which does seem to address the same issue but using the setInterval function as #Matt Ball has laid out there doesn't work at all for some reason. I'm using the code below where 'div.enrollment' is meant to find in the DOM which is dynamically loaded and execute..
jQuery(window).load(function ($)
{
var i = setInterval(function ()
{
if ($('div.enrollment').length)
{
clearInterval(i);
// safe to execute your code here
console.log("It's Loaded");
}
}, 100);
});
Any help on guidance on this would be greatly appreciated! Thanks for your time.
It seems that the healcode.js is doing a lot of stuff. There is a whole lot of markup added to the <healcode-widget> tag.
I would try to add another tag with an id inside and test for its existence:
<healcode-widget ....><div id="healCodeLoading"></div></healcode-widget>
Test in an interval for the existence of healCodeLoading inside <healcode-widget>: (Assuming jQuery)
var healCodeLoadingInterval = setInterval(function(){
var healCodeLoading = jQuery('healcode-widget #healCodeLoading');
if (healCodeLoading.length == 0) {
clearInterval(healCodeLoadingInterval);
// Everything should be loaded now, so you can do something here
}
}, 100);
healcode.js should replace everything inside <healcode-widget></healcode-widget> during init. So, if your <div>-element is no longer inside, the widget has loaded and initialized.
Hope that helps.
If you just want to load some markup and content and then run some script afterwards, you can use jQuery. You should use something like the following in script#1 to run a function in script#2
$.get( "ajax/test.html", function( data ) {
// Now you can do something with your data and run other script.
console.log("It's Loaded");
});
The function is called, after ajax/test.html is loaded.
Hope that helps
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.
This is what I have in :
<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">testfunction("hello");</script>
Inside myscript.js:
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = 'jquery-1.9.0.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
function testfunction(str) {
$(document).ready(function () {
alert(str);
});
}
Of course jQuery is not needed for the current testfunction, but it will be needed. Using this approach, jQuery is downloaded but NOT loaded to the browser when calling to testfunction() (Uncaught ReferenceError: $ is not defined).
What I could do is to load jQuery in a different script before my JS is loaded. In that case, it will work, but I would have three different scripts and that seems to be not elegant in my honest opinion.
Is there any other way to achieve this?
Thanks!
You might want to try looking at this answer. It may not be waiting until jQuery is fully loaded.
With your code, the script will be loaded asynchronously. You need to add to the script tag an onload event that will trigger the parts that are dependent on jQuery.
If you want the script to be loaded in a synchronous way, use document.write:
window.jQuery||document.write(unescape("%3Cscript src='"+jQueryURL+"' type='text/javascript'%3E%3C/script%3E"));
The document.write technique is very common, just keep in mind that you cannot use it after your document has loaded (or else it will overwrite the whole page).
If you want to use dynamic loading on a larger scale, look at existing loader or AMD libraries.