普通javascript中不显眼的onload的最佳方式 [英] best way of unobtrusive onload in plain javascript

查看:73
本文介绍了普通javascript中不显眼的onload的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在普通javascript中加载页面后调用内容的最佳不引人注目的方式是什么?当然在jquery中我会使用

what is the best unobtrusive way of invoking something after the page is being loaded in plain javascript? of course in jquery i would use

$(document).ready(function(){...});

但我不确定普通js中最可靠的方法。

but i am not sure about the most reliable approach in plain js.

明确

window.onload = ...

不是正确的解决方案,因为它会覆盖以前的声明。

is not proper solution, because it would overwrite previous declaration.

我在尝试什么要做的是在加载页面后将iframe插入到div中,但实际上可能有更好的方法。我的计划是做类似的事情

what I am trying to do is to insert an iframe into a div after the page is loaded, but maybe there are actually better ways of doing it. My plan is to do something like

window.onload = function(divId){
 var div = document.getElementById(divId);
 div.innerHTML = "<iframe src='someUrl' .. >";
}

编辑:
因不包括所有必要细节而道歉。
该脚本不适用于我的网站 - 我的想法是在外部网站上显示我网站的一部分(表格)。优先考虑的是尽量减少某人为使用我的代码而付出的努力。这就是为什么我想将所有内容保存在js文件中,而< script> 中除了< script src =http: //my.website/code.js/> 。如果我更改iframe的url或者我想添加一些功能,我想更新所有其他网站上的代码而不要求他们进行任何更改。

我的方法可能是错的 - 任何建议非常欢迎。

apologizes for not including all necessary details. The script is not for my website - the idea is to show a part of my site (a form) on external web sites. The priority is to minimize the effort someone has to put to use my code . That is why I would like to keep everything in js file and absolutely nothing in <script> - except of <script src="http://my.website/code.js" />. If I change url of an iframe or i would like to add some features, I would like to update the code on all other web sites without asking them to make any changes.
My approach might be wrong - any suggestions are very welcome.

推荐答案

//For modern browsers:
document.addEventListener( "DOMContentLoaded", someFunction, false );

//For IE:
document.attachEvent( "onreadystatechange", someFunction);

`attachEvent` and `addEventListener` allow you to register more than one event listener for a particular target.

请参阅:
https://developer.mozilla.org/en/DOM/element.addEventListener

还绝对值得一看jQuery如何做到这一点:$ b​​ $ b http://code.jquery.com /jquery-1.7.js 搜索 bindReady

Also definitly worth looking at how jQuery does it: http://code.jquery.com/jquery-1.7.js Search for bindReady.

这篇关于普通javascript中不显眼的onload的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆