How to load a js file after loading html? - javascript

After i load this :
$('#buy-div').load('../buyBar/buyBar.html',function() {
//do some things here
});
I would like to include this :
<script src="../buyBar/BuyBar.js"></script> //access some html that does not exist
Beacuse in this js i am looking for some html that does not exist only after the .load function is done. (such as getElementById or $('input').keyup(function() { that happens before the .load was finished.

Just put the code that you want to run after the html is loaded in a function. Then call that function in the callback function of the .load('../buyBar/buyBar.html')
Assume "../buyBar/BuyBar.js" originally contains
document.getElementByID("#someElement").innerHTML = "...";
You can change it to
function someFunction(){document.getElementByID("#someElement").innerHTML = "...";}
Now just put <script src="../buyBar/BuyBar.js"></script> in the <head> as usual. Then do this:
$('#buy-div').load('../buyBar/buyBar.html',function() {
someFunction();
//do other stuff
});

I figure out i can do it by loading it when .load is done :
let script = document.createElement('script');
script.src = "../buyBar/Pay.js";
document.body.append(script);
This works but i am not sure is the best solution.

Related

Executing script written inside the div when the div dynamically loads on to the page

I have a div which looks like
<div>
//Useful content
<script type="text/javascript">
function(){
//some useful code
}
</script>
</div>
Now am getting this div as a response of an Ajax call and appending that into body. Now when the gets appended to body, the function inside the script tag should get executed. But not.. what is the problem here?
You should be using document.createElement("script"); if you need to insert some script dynamically. This is recommended approach.
Anyway, following code is working just fine for me:
var str = "<script>alert('Hi!');</scr"+"ipt>";
$('#container').append($(str)[0]);
Make sure you escape you script properly.
Your function is not executing because it is not being called.
You should use a self-executing function that will just run as soon as it's loaded:
(function() {
alert('hello world!');
})();

Append script in head by jquery

I want append script in head if there is tag <script> in the body, i try as following but it don't work, How can done it?
DEMO: http://jsfiddle.net/rYXJx/
JS:
var TAREA = $('body').find('textarea').length;
if(TAREA > 0){
$('head').append('<script type="text/javascript" src="files/js/nicEdit.js"></script><script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script>');
};
You can use jquery getScript function:
http://api.jquery.com/jQuery.getScript/
so the correct code looks like the below:
$.getScript('files/js/niceEdit.js');
One of the problems in your script is that the </script> inside the string literal actually breaks the outer <script> tag. You might notice these characters in your page which seem to come out of nowhere:
');};
Secondly, while it is still possible to inject a <script> tag in the head, there is no direct/easy/cross-browsr way of knowing when the script has finished loading. And you cannot use a script before it is loaded completely.
Best solution is to use jQuery.getScript() which provides a callback. Use the callback to call nicEditors.allTextAreas() function:
$(document).ready(function () {
if ($("textarea").length > 0) {
$.getScript("files/js/nicEdit.js", function () {
// no need for onDomLoaded -- DOM is loaded at this point!
nicEditors.allTextAreas();
});
}
});

jQuery on the bottom, wait execution script on <head> until it is loaded

I saw similar question here in SO, where someone wants to do the same thing. The different case is that I have this lightweight script that listens for event bubbling to the top of the document root that I intentionally want to put on the top of the page and I dont want to wrap it inside $(document).ready(). It looks something like this:
<html>
<head>
<script>
document.documentElement.onclick = function (e) {
//$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
}
</script>
</head>
And then near the bottom of the page I include jQuery like this:
<body>
<script src="./jQuery.js"></script>
</body>
</html>
As you can see on the <head> when I'm making an ajax call to somewhere using $.ajax, it's possible that jQuery is not yet loaded, so that it may throw $ is undefined error when someone clicks on something on DOM, and jQuery is not loaded yet. My workaround is probably to use settimeout hoping that jquery will be loaded sometime later and the code is working like this:
if (typeof $ === 'undefined'){
setTimeout(doAJAXJquery, 50);
}else{
$.ajax(//blablabla) //jQuery loaded and ready to use!!
}
But it's a really dirty hack. How am I supposed to know when jQuery is finished loading? that 50ms i put there is only an arbitrary value i made up myself. Of course it is still not gonna work if jquery hasn;t been loaded yet and it already passes 50ms.
Is there any better workaround so when jQuery is undefined, it is gonna retry sometime later again, or put a function that executes ajax inside some callback that gets executed when jQuery is ready? thanks.
what about
<head>
<script type="text/javascript">
var init = function(){
document.documentElement.onclick = function (e) {
//$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
}
}
</script>
</head>
<body>
<script src="./jQuery.js"></script>
<script type="text/javascript">
init();
</script>
</body>
If you want to execute the list of functions (or events 'fired') waiting for jQuery to load you could create your own 'ready' function :))
var runList = new Array(), timer = setInterval(function(){
if (typeof(jQuery) != 'undefined')
{
clearInterval(timer);
if (runList.length>0) for(var i in runList) runList[i]();
}
}, 50);
runList.push(function(){alert(1);});
runList.push(function(){alert(2);});
var jQuery = 1;

Calling external js function from another external js file gives "Undefined" error

I have this code in plugins.js:
$(document).ready(function() {
watermark = function(elemId, text, hoverClass, normalClass, parentId){
// onFocus event
$("#"+elemId).focus(function(){
($(this).val()==text)
$(this).val('');
(parentId!=0)
byId(parentId).className = hoverClass;
});
// onBlur event
$("#"+elemId).blur(function(){
($(this).val()=='')
$(this).val(text);
(parentId!=0)
byId(parentId).className = normalClass;
});
}
});
Then I have this in the index.js file:
new watermark("footer_contact_name", "Name", "footer_form_text_active", "footer_form_text", "footer_form_field_1");
Everything works when written in the same js file, but when calling it like this from the index.js file, I get an undefined function error in FireFox, using Firebug to debug.
Any ideas?
Thanks
BTW: I include these in index.html like this:
<script src="scripts/plugins.js" type="text/javascript"></script>
<script src="scripts/index.js" type="text/javascript"></script>
You need to call the function after the document gets ready - wrap it in:
$(document).ready(function() { });
The watermark functions gets declared when the DOM is ready to be manipulated (inside $(document).ready(function(), therefor won't be available the moment your index.js gets included.
EDIT:
You kind of have to make the call to watermark after the DOM is ready to be manipulated, since it uses elements in the DOM. A solution would be to declare your watermark function outside the $(document).ready(function(), and then call it from index.js inside a $(function() { (shorthand for $(document).ready()):
functions.js:
watermark = function(elemId, text, hoverClass, normalClass, parentId){
// function logic
}
index.js:
$(function() {
new watermark("footer_contact_name", "Name", "footer_form_text_active", "footer_form_text", "footer_form_field_1");
}
You're only defining the watermark() function after the DOM is loaded. You could define it outside the $(document).ready() call and you could embed the $(document).ready() call inside it, so it will execute when the DOM is loaded, but be available before that.
For example:
watermark = function(elemId, text, hoverClass, normalClass, parentId) {
$(document).ready(function() {
/* ... */
}
}

Loading an external script after page load with jQuery

I'm a little confused how to do this, basically I have a page that has a Facebook Share button inserted via JavaScript:
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
The problem is that it's blocking the page load at that part, how can I insert this tag after page load and still have the script execute? I'll like to do it in an unobtrusive way, ideas?
Use the jQuery getScript command inside $(document).ready. This will download the script after the page has loaded. Example:
$(document).ready(function() {
$.getScript("http://static.ak.fbcdn.net/connect.php/js/FB.Share", function() {
alert("Script loaded and executed.");
});
});
You could use the jquery.getScripts to load it asynchronously.
Try something like this:
$(document).ready(function() {
var script = document.createElement( 'script' );
script.src = "http://static.ak.fbcdn.net/connect.php/js/FB.Share";
script.onload=optionallyDoSomethingWithTheScriptYouJustLoaded();//not needed
var headID = document.getElementsByTagName("head")[0];
headID.appendChild(script);
});
Inject the script tag into the dom as a callback of the document ready event.
you could do something like:
$(function() {
$.getScript('http://static.ak.fbcdn.net/connect.php/js/FB.Share', function() {
//do nothing here
});
});

Categories

Resources