Load javascript after page load - javascript

I have an external javascript that contains something like:
document.writeln("<script type='text/javascript' src='...'></script>");
In the original html i have something link
<div id="banner">
<script type="text/javscript" src="<the external javascript above>"></script>
</div>
How can i load that delayed?
I've tried using window.setTimeout and append that javascript but its not working.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
Thank you.

You can call your injection code on window.onload.
window.onload = function() {
inject();
doSomethingElse();
};
window.onload will wait until all assets have finished downloading, such as images and scripts. After scripts are downloaded, you can inject your code to page.

Maybe a better way to do it would be to add a delay to the script.
Also, if you use something other than 'document.writeln' for example:
$('#banner').append(...);
you can better direct where it goes.

There is an open source javascript library for doing this kind of thing: http://labjs.com/
I have used it in the past and it worked very well.

Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
That is not entirely true. Especially if the div is empty you could simply use: document.getElementById('banner').innerHTML = "<h1>HTML-Output here.</h1>"
Bukko's answer would work as well if you are using jQuery. My answer is pure Javascript. With this newfound freedom you should be able to simply put the loading of your script at the bottom of the page or use a custom body.onload() function
Edit: or simply follow Samet's suggestions in conjunction with the .innerHTML. Hope this helps.

Related

Is there any jquery to detect if the html tag was not closed? or page has not completely loaded?

I'm experiencing an issue (which I still need to fix) where my entire page does not load. It gets cut off in the middle of an element.
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
I was thinking of just putting <div id="end_of_page"></div> at the bottom of the page, and checking if that was rendered, if not, i'll know something went wrong and can reload to try again.
thanks!!
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
You can do that, yes. Put this in the head after including jQuery:
<script>
jQuery(function($) {
if (!$("#end_of_page")[0]) {
// Something went wrong, load again
location.reload();
}
});
</script>
You'll enter the body of the loop (and so, force a reload) if the end_of_page element doesn't exist as of when the jQuery ready event fires (which is meant to be when the page is done loading).
But: Better by far to figure out why your page is getting cut off half-way through and solve that. This sort of workaround is not a solution.
You can use
$(document).ready(function(){
// code here
});
that code will only run when the page has loaded. A convenient shorthand is:
$(function(){
// code here
});
assuming your jQuery object is $. To finish your requirement, you can have a variable that is set within the load function, then use a timer set at the start of the page to check for it. If it's not there, reload.
Personally, I think you should invest some time into figuring out why your pages only half-way (Firebug or the Chrome Inspector may help you do this, it might be a resource in your page that is causing it to hang, and since most HTTP requests are only made 2 at a time per hostname, it might be waiting for that to return before fetching the rest).
Might be a server-side issue OR some script or library is stealing your fish $ (AKA: 'Dollar').
I'll rather suggest you to debug your code instead of refreshing the page trying to fix issues.
Make sure your scripts are in the head of your document, and jQuery + your jQ functions right before the closing </body> tag wrapped in:
(function($){ /*your functions*/ })(jQuery);

Do I still need $(document).ready(function(){ })?

I've been developing in javascript for a few months and I have been using $(document).ready(function(){ at the beginning of all my scripts. I've noticed other folks don't use this in their scripts but I can't seem to get mine working without it. I'd like to keep my code cleaner, but for all my google searches I can't seem to figure out how to get rid of it.
I know it tells the browser to execute my script as soon as the page loads but is there something global I can set so that I don't need to explicitly tell the browser to execute each of my scripts when the page loads? Or is it a more global problem with where in my html files the scripts are located?
You're needing document.ready probably because you're interacting with the DOM before it loads. How can the script manipulate elements that are not there yet?
If you stick your script at the end of the file you will not need it. It's also good practice to do so for a lot of Javascript files as they can take time to process (especially if they're hosted externally). Putting them at the end of the file often speeds up the page load time.
All $(document).ready(function() { ... }); or $(function() { ... }); does is wait for the document to be ready for manipulation. You should use $(document).ready(function() { ... }); or $(function() { ... }); if your scripts are inline or in the <head /> section because JavaScript executes in the order in which it appears on the page otherwise.
To do away with $(document).ready(function() { ... }); or $(function() { ... });, simply move your scripts down to the bottom of the page after all of your content, right before the closing </body> tag.
Putting the scripts at the bottom is really a best practice anyway. For this and other best practices, I recommend you take a look at Html5Boilerplate and Yahoo! Best Practices.
the $(document).ready() convention is part of jQuery, not just JavaScript. From their' documentation on the ready function:
This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
So yes, it is required. jQuery does come with a shorthand for this though, so you could do the following:
$(function() {
//jquery code
};

How to run scripts loaded dynamically with javascript

I was wondering if there is a way to execute script within a ajax dynamically loaded content.
I've searched the web and this forum also an find a lot of answers, like
[Running scripts in an ajax-loaded page fragment
[1]: Running scripts in an ajax-loaded page fragment [1]
But none of this seems to work fine for me.
I'm not experienced as the author of the quoted post, so maybe we can find a solution more simple and quite for everyone.
For now i've implemented a tricky turnaround that smell to much of an hard-coded solution that is:
//EXECUTE AJAX REQUEST LET'S SAY SUCCESSFULLY,
$ajax([..]) //THEN
.ajaxSuccess(function(){
// LOCATE ANY OBJECT PRE-MARKED WITH A SPECIFIC CLASS
$(".script_target").each(function()
{
//DO SOMETHING BASED ON A PRESET ATTRIBUTE OF THIS SPECIFIC ELEMENT
//EXAMPLE: <div class=".script_target" transition="drop_down">...</div>
//WILL FIRE A SCRIPT RELATED TO drop_down CASE.
});
});
I know this is an ugly solution but i didn't came up with nothing better than this.
Can you help to improve this method?
Maybe there's a way to let the browser fire script within the loaded page automatically?
PS. I'm not going to use the eval() method if it's not the last solution, cause both security leak and global slowdown, AND be aware that the script launched need to modify objects loaded in the same fragment of the script.
Thanks in advance.
If I understand you correctly :
you use "load" to retrieve html content from the server, and you add it to the page.
later, you do an ajax call, and on the return of the ajax call, you want to act on the markup you added earlier
but, depending on the markup retrieved, you want to do something different in the ajax callback
So another question : before you load the markup, do you know what logic will be behind it, or do you actually need to "read" the returned HTML to understand what it will be used for ?
Otherwise maybe something like this would work :
In the callback of the "$.load" function, use $.data() to attach more information to created dom object
In the ajax callback, you should be able to access the "added" markup (with a class like you did, or with an id if possible), and read to "data" to known which behavior you should have ?
Hopefully I got your problem right, it could help if you were able to create a jsfiddle or something, just to make sure we understand it.
Hoping this helps.
EDIT : After your comment, it might be related to the selector you use when calling $.load().
There is a "Script Execution" section in the $.load documentation : http://api.jquery.com/load/ , that explains that the scripts are not executed if you add a selector in the url, like this :
$('#b').load('article.html #target');
Could this be your issue ?
Also, if possible, you could try and change your site so that instead of having the js code of each "page" of the gallery inside the page, you put it inside a separate javascript file, that you load at runtime (for example with require js).
This way, "loading" a page would be something along the lines of :
$.load("url_of_a_page_markup.html", function () {
require(["url_of_the_javascript_module.js"], function (TheJsModuleForThePage) {
TheJsModuleForThePage.doSomething();
});
});
If you structure your JS modules in a consistent way, and you define a convention for the name of markup and js files, you can generalize things so that a "gallery" manager deals with all this code loading, and you'll end up with well isolated js modules for each page.
Hoping this helps.
If you want to run a script in a ajax loaded page fragment you can use try to use jQuery.load function.
Have you considered a module loader like require.js or Lab.js?
There are many other people asking similar questions:
does anyone knows good ajax script loader
Where are scripts loaded after an ajax call?
getting jQuery scripts and content through ajax dynamically
dynamic script loader in JS
Edit: I think I misread your question. Will try and come up with a better answer. Sorry!
Best of luck to you!
I came across this same issue when I dynamically loaded some HTML to use inside a JQuery UI dialog (a help function for my application).
$('#helpMessage')
.load('./help/' + helpFile, function () {...do stuff after loading});
To make things simple I wanted to combine the unique script related to the help page within the HTML fragment that I load. Using the examples on the JQuery UI page I created a dialog with a Jquery UI button element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Icons</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
(function() {
$('#myButton') // My button element
.button() // Initialize it as a JQuery UI button object
.click(function (){ // Hook up the button click event
$('#correct')[0].play(); // to play a sound in an <audio> tag
});
});
</script>
</head>
<body>
This is my help file, this is my code. This is for reading, this is for fun.
<button id="myButton">Button Text</button>
</body>
</html>
The dialog would load and the HTML displayed, but the embedded script did not execute.
I realized that one simple change would fix it. The script is embedded in an anonymous function (a best practice and part of the JQuery UI demo code). By immediately invoking the anonymous function the script executed when I loaded the HTML fragment into my main page.
This:
<script>
(function() {
...
});
</script>
Became:
<script>
(function() {
...
})(); // Immediately invoke
</script>
Niceness.

Can I disable Chrome/Webkit parallel CSS & JS download feature?

I'm experiencing the documented bug where webkit browsers render the page incorrectly on first load because the javascript is executing before the css has finished downloading (due to them being downloaded in parallel).
While a quick refresh fixes the look of the page, that solution is inadequate for my problem (I run command-line utilities that take screenshots of our pages, but these utilities don't have the option to "refresh" a page before taking the screenshot)
Does anybody have any suggestions or solutions for ensuring that the css-include is loaded in it's entirety before the javascript-include and inline-javascript are executed?
Thanks! -Dan
EDIT-- Not using a library. Just good 'ol javascript.
If you are using a library I think most of them allow you to do this. It's easy with jQuery, if not you can use a <script defer="(x number of second)">Function()</script> at the end of hte page. You may also consider moving the javascripts to the bottom of the page where possible. js Best Practices.
+1 for putting your scripts at the bottom of the page, also might try putting your script in the window.onload event:
<script >
function myCode(){
// do something
alert('test');
}
window.onload = myCode;
</script>
I'm not 100% sure whether the onload event will wait until the .css file is loaded though. but it's easy to try.

way to load javascript code in web page

I prepare a project with a simple webpage, canvas, and javascript files that run game in the canvas. I want load my code when page starts, what is best way?
put body onload?
startup code in body of .js file (not in function)?
attach to window load event?
use some jquery capability?
Thanks!
You can attach to when the page loads using jQuery like this:
$(function() {
// Your code here.
});
If that's the only thing you'd be using jQuery for, though, I'd probably stick with your third option you listed there.
Javascript and jQuery code is generally best put right before the </body> tag.
Use $(document).ready
$(document).ready(function() { code goes here; } );
Since you are using jQuery, you should use the facilities it provides..
$(document).ready(
function(){
/*You code goes here..*/
});

Categories