How to dynamically include a html file containing javascript - javascript

in my website i have a simple navigation bar where clicking on the different items causes the main content to change. Technically, all is done in a single file "main.html", which contains everything and i use the jquery function "load" to dynamically load other html files to place it inside the main.html. This works just fine as long as there is no javascript in these html files i embedded. But there is one file i want to embedd, which has also javascript code in it, which should get executed on $(document).ready. But this never happens - there is no error in the javascript, it just never gets executed. I suppose it's because i only change the DOM of the "main.html" and then there will be no "onReady" event fired. Can someone give me some idea of what would be the best way to get the desired behaviour? Placing the javascript in the "main.html" would cause things to work, but this is no option for me.
Thanks in advance!
update: problem solved
Problem is solved. When i call the javascript outside the onReady() event (as Loic Coenen suggested), it works just as excpected. I also removed the tags wrapped around. Many thanks to all who helped me!

You can trigger a custom event to notify your other.html script that the tree is loaded. I haven't tried it, but I would use something like that :
In main.html:
$('#div_to_load').load('other.html',{},function(){
$('#div_to_load').trigger('loaded')
})
In other.html
$('#div_to_load').on('loaded', function(){
// Code to execute
})
I don't know if that could do the trick.
Edit : I asume that the javascript directly included in your other.html is executed anyway.

you are in main.html that contains a head, body. the problem might be that when you load the page your other page also has a head, and body and so on, if you are loading onto a div, it should be only code, can be javascript aswell, but no head or body. but if you resist, here is your solution
$("#loadnewpagebttn").load(location.href+" foobar ",function(){
$.getScript("js/yourscript.js");
});
you need to create a script file for that page and load it. inline scripts are some what of a bad habit anyways
full example:
jQuery.getScript( url, [ success(data, textStatus) ] )
url - A string containing the URL to which the request is sent.
success(data, textStatus) - A callback function that is executed if the request succeeds.
$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});
http://api.jquery.com/jQuery.getScript/

Related

JavaScript Will Not Load After DOM

I'm having trouble getting my JS to run after all my content has loaded. Right now on the site Im working on: http://hsvgridproject.com, the grid will not load the first time a user visit the site and needs a hard refresh before it will work. I believe I need to use a window.onload function of some sort but as I am still learning Java I'm not sure how to implement it into my project without breaking the code.
The script for the grid on homepage has a window tag surrounding it already (credit Codrops):
(function(window) {
Please let me know if you need more info. Thank you!
It's probably not working because you're executing your script before the DOM is fully loaded.
To ensure it's executed after the DOM is fully loaded, either move the script tag which executes your code right before the closing tag of the body element or use DOMContentLoaded event like this:
document.addEventListener("DOMContentLoaded", function(event) {
// execute your code
});

Jquery Document.ready when loaded through AJAX links

I am new here, so please pardon any beginner mistakes.
I am learning jQuery (v1.9.1) along with using jQuery Mobile (v1.3.1). I am encountering two problems when using AJAX links and javascript:
1) When I link pages through the default AJAX linking method that jqm offers, I lose the capability of running any newly loaded javascript on the subsequent pages. i.e. When I go from page1.php to page2.php, can I execute javascript namely something like the following (this code is in page2.php):
<script>
$(document).ready(function(){
$('#form_field_email').focus();
});
</script>
After browsing through bunch of questions here, I believe it is because no new script is evaluated after initial page load. Therefore, I tried to move all my code into on .js file, which I load on page1.php. But sometimes I want to trigger actions on-page-load (as noted above).
Is there any way to achieve this without using eval function?
2) On a similar note, if the id of a DIV on page1.php was 'messageBox', but if I use the same id for another DIV on page2.php, I lose the capability of controlling the newly drawn DIV on page2 as the javascript still points to the old DIV which is no longer visible.
$('#messageBox').show();
Is there a way to use the same name but still be able to point to the elements on the current page.
Thank you for your help.
What you should do is place the code that needs to run after the ajax has loaded in a success callback for the ajax call.
$.ajax({
url: 'http://example.com',
success: function() {
//do something when call completes successfully
}
);

loading a js file asynchronously from a js file that loads asynchronously

I had a javascript file(initial.js) on the page inserted through the script tag like so:
<script src="initial.js"></script>
This file creates dom elements(let say two links) and also loads another jQuery plugin(plugin.js) asynchronously via jQuery ajax method. Clicking on those two links brings up a module from the jQuery plugin(plugin.js).
The javascript file(initial.js) was then modified to load asynchronously on the page via jQuery ajax instead of via script tag. This has resulted in some events not getting attached to the links intermittently and this results in the plugin not being called.
I believe the browser is loading the async scripts in its own order and hence the links fail to launch the plugin intermittently. Any pointers to resolve this issue with this new set up?
At a high-level, I think you need to look into something like require.js. Alternatively, you could look into some jQuery event handling code which allows you to listen on load events of calls which may help you determine when one script loaded before loading the next one.
You have probably tried something like this in the past:
var output;
$.get('data.php',function(data){
output=data;
});
alert(output);
You will get an undefined error because Javascript doesn't wait around for the AJAX call to be returned before moving onto the next code.
Same thing goes for scripts. If you place multiple calls to multiple scripts, you will probably get the smallest one returned the quickest, and that script executed. If you load a script that is 10kb and then one that is 1kb, the 1kb script will probably return the quickest and then be executed even though it was called after the 10kb script.
To correct this, you could make a queue system and then only load each script after the previous has loaded:
var scripts=['script1.js','script2.js','script3.js'];
$(document).ready(function(){
loadScript();
});
function loadScript(){
if(sendQueue.length==0)
return;
$.getScript(scripts[0],function(){
scripts=scripts.slice(1);
loadScript();
});
}
But if you are loading scripts from within scripts from within scripts... very Inception like, then this still may not work.

Reload entire page with AJAX request and changed GET parameters

I'm trying to reload an entire page with a jQuery AJAX request (supplying a simple GET parameter to the load), roughly in this fashion.
$.ajax({
url: "site.php?param="+new_param,
cache: false,
success: function(content) {
$("html").html(content);
}
});
As you can see, this will cascade the <html> blocks and somehow the styling gets broken (background is suddenly white and so on).
Tricks like $(document).html(content); won't work either.
Unfortunately I haven't found any solution to this problem, yet.
If you are not reloading head content (loading new javascript or css), and I see no reason why you should do such a thing, you should really try to contain your content loading to content itself, ie. <body>.
$("body").html(content);
Edit
In order to achieve, what I think you are trying to, you could check out https://github.com/defunkt/jquery-pjax
The problem with loading a full HTML page is that you only get the HTML code but the JavaScript is not interpreted, and the paths to the CSS files get messed up.
Imagine if you will: you are inside the index.php file and the CSS files are located in the same directory. Now if you load a different HTML file using AJAX, and output that code inside a div, maybe that file points to the "../css/random_dir/style.css" file. Now that path is not good inside your index.php file, and that's why the styling gets messed up.
Your new code would expect to find the "background" inside a css file that is not loaded (and will not be loaded).

Inserting a script dynamically in the DOM

I'm trying to understand why this code doesn't work and the alert output is just blank.
<script type="text/javascript">
(function() {
...
var s = document.getElementsByTagName('script')[0]; alert(s.innerHTML);
s.parentNode.insertBefore(res, s);
...
})();
</script>
It should add res before s if I'm not wrong. That's what I specifically need, as I tried to append it to body and it's added successfully (after doing that though I have to run some code inside this function, so if the script is not loaded before it, such code will error).
This function should run when document is loaded or is that the problem? In particular, the getElementsByTagName function seems to not return anything.
Thanks to everyone.
You cannot run this type of code before the document is loaded. This code has to be loaded before it can be run (see the circular argument here). And, by then, much of the rest of the document has been loaded. You can dynamically load scripts AFTER the document has been loaded. If you need a script loaded before other scripts, then you either have to put them all in the document statically in the order you need them to be run or you need to add them all dynamically in the order you need them to run and you will need to keep track of completion of one load before loading the next.
If you care to describe the broader problem you're trying to solve, we can probably suggest a more elegant solution than what you are pursuing.

Categories

Resources